我似乎无法弄清楚这段代码有什么问题。
我试图使用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);
}
}
你的代码是在略有不同的位置(从(30, 30)
到(0, 1)
)绘制相同大小的(2, 2)
的4个矩形,因为你只是使用数组索引器作为Locaton坐标。
简单的解决方案,使用您现在显示的Rectangle.Size
值:
将(X, Y)
的Rectangle.Location
值增加一个由Rectagle Height
和Width
定义的偏移量,将矩阵中的当前(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);
}
}
}
}
有了这个矩阵:
private int[,] matrix = new int[3, 3] {
{ 0, 1, 0 },
{ 0, 1, 0 },
{ 1, 1, 1 }
};
你得到这个: