C # raster padding

I want to create a 160 * 160 bitmap and split it into four squares with each square filled with one color. How can I do that?

+3
source share
2 answers

Just in case, if someone needs a method that solves this particular problem in a more general way, I wrote an extension method using colors and an integer, which indicates how many fragments it should separate in the x and y directions:

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 required by the OP will be created using:

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

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");
}
+3
source

Source: https://habr.com/ru/post/1741556/


All Articles