为什么此代码绘制的是框而不是L形?

问题描述 投票:2回答:1

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

我试图使用2D数组绘制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);
           }
}
c# arrays winforms rectangles system.drawing
1个回答
2
投票

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

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

(X, Y)Rectangle.Location值增加一个由Rectagle 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 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

有了这个矩阵:

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

你得到这个:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.