如何使用二维数组来描述形状来绘制形状?

How to draw shapes using a 2D array to describe the shape?

我似乎无法弄清楚这段代码有什么问题。

我正在尝试使用二维数组绘制 L 形状。出于某种原因,代码绘制了一个大盒子而不是 L 形状。我逐步检查了代码,(x, y) 位置没问题。
我不确定我做错了什么。

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);
           }
}

您当前的代码是在稍微不同的位置(从 (0, 1)(2, 2))绘制 4 个相同大小 (30, 30) 的矩形,因为您只是使用数组索引器作为 Location 坐标。

简单的解决方案,使用您现在显示的 Rectangle.Size 值:

Rectangle.Location(x, y) 值增加由矩形的 HeightWidth 定义的偏移量,乘以当前 (x, y) 在这些偏移量的矩阵:
(注意x索引是用来乘以高度偏移的;当然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 aCanvas_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);
            }
        }
    }
}

有了这个矩阵:

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

你明白了: