简体   繁体   中英

c# bitmap filling

I want to create a bitmap of size 160*160 and split it into four squares with each square filled with one color. How can this be done?

Just in case anyone needs a method solving this specific problem in a more general way, I wrote an extension method, taking colors and an integer that states how many tiles it should split off in x and y direction:

public static void FillImage(this Image img, int div, Color[] colors)
{
    if (img == null) throw new ArgumentNullException();
    if (div < 1) throw new ArgumentOutOfRangeException();
    if (colors == null) throw new ArgumentNullException();
    if (colors.Length < 1) throw new ArgumentException();

    int xstep = img.Width / div;
    int ystep = img.Height / div;
    List<SolidBrush> brushes = new List<SolidBrush>();
    foreach (Color color in colors)
        brushes.Add(new SolidBrush(color));

    using (Graphics g = Graphics.FromImage(img))
    {
        for (int x = 0; x < div; x++)
            for (int y = 0; y < div; y++)
                g.FillRectangle(brushes[(y * div + x) % colors.Length], 
                    new Rectangle(x * xstep, y * ystep, xstep, ystep));
    }
}

The four squares, the OP wanted would be produced with:

new Bitmap(160, 160).FillImage(2, new Color[] 
                                  { 
                                      Color.Red, 
                                      Color.Blue, 
                                      Color.Green,
                                      Color.Yellow 
                                  });

You can try something like

using (Bitmap b = new Bitmap(160, 160))
using (Graphics g = Graphics.FromImage(b))
{
    g.FillRectangle(new SolidBrush(Color.Blue), 0, 0, 79, 79);
    g.FillRectangle(new SolidBrush(Color.Red), 79, 0, 159, 79);
    g.FillRectangle(new SolidBrush(Color.Green), 0, 79, 79, 159);
    g.FillRectangle(new SolidBrush(Color.Yellow), 79, 79, 159, 159);
    b.Save(@"c:\test.bmp");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM