1 回答

TA貢獻1802條經驗 獲得超5個贊
(30, 30)您當前的代碼是在略有不同的位置(從(0, 1)到)繪制 4 個相同大小的矩形(2, 2),因為您只是使用數組索引器作為Location坐標。
簡單的解決方案,使用Rectangle.Size您現在顯示的值:
(x, y)將 的值增加Rectangle.Location由矩形Height和定義的偏移量,將矩陣中Width的當前位置乘以這些偏移量:( 請注意,索引用于乘以高度偏移量;當然與 相反)(x, y)
xy
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 }
};
你得到這個:
- 1 回答
- 0 關注
- 102 瀏覽
添加回答
舉報