I cannot seem to figure out what is wrong with this code.

I am trying to draw an L shape using a 2D array. For some reason, the code is drawing a big box instead of an L shape. I stepped through the code and the (x, y) positions are fine.
I am not sure what I am doing incorrectly.

private int[,] matrix = new int[3, 3] {
    { 0, 1, 0 },
    { 0, 1, 0 },
    { 0, 1, 1 }
};

private void aCanvas_Paint(object sender, PaintEventArgs e) {
    var gfx = e.Graphics;
    var brush = new SolidBrush(Color.Tomato);
    for (var x = 0; x <= matrix.GetLength(0) - 1; x++) 
        for (var y = 0; y <= matrix.GetLength(1) - 1; y++)
           if (matrix[x, y] != 0) {
               var rect = new Rectangle(x, y, 30, 30);
               gfx.FillRectangle(brush, rect);
           }
}

1 Answers

2
Jimi On Best Solutions

Your curent code is painting 4 rectangles of the same size (30, 30) at a slightly different location (from (0, 1) to (2, 2)), since you're just using the array indexers as the Locaton coordinates.

Simple solution, using the Rectangle.Size value you're showing now:

Increment the (X, Y) values of the Rectangle.Location by an offset defined by the Rectagle Height and Width, multiplying the current (x, y) positions in the matrix by these offsets:
(Note that the x index is used to multiply the height offset; of course the opposite for y)

private int[,] matrix = new int[3, 3] {
    { 0, 1, 0 },
    { 0, 1, 0 },
    { 0, 1, 1 }
};

Size rectSize = new Size(30, 30);
private void panel2_Paint(object sender, PaintEventArgs e)
{
    int xPosition = 0;
    int yPosition = 0;
    using (var brush = new SolidBrush(Color.Tomato)) {
        for (var x = 0; x <= matrix.GetLength(0) - 1; x++)
        for (var y = 0; y <= matrix.GetLength(1) - 1; y++)
        {
            xPosition = y * rectSize.Width;
            yPosition = x * rectSize.Height;

            if (matrix[x, y] != 0) {
                var rect = new Rectangle(new Point(xPosition, yPosition), rectSize);
                e.Graphics.FillRectangle(brush, rect);
            }
        }
    }
}

enter image description here

With this matrix:

private int[,] matrix = new int[3, 3] {
    { 0, 1, 0 },
    { 0, 1, 0 },
    { 1, 1, 1 }
};

You get this:

enter image description here