猿问

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

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


我正在尝试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);

           }

}


慕勒3428872
浏览 67回答 1
1回答

慕后森

(30, 30)您当前的代码是在略有不同的位置(从(0, 1)到)绘制 4 个相同大小的矩形(2, 2),因为您只是使用数组索引器作为Location坐标。简单的解决方案,使用Rectangle.Size您现在显示的值:(x, y)将 的值增加Rectangle.Location由矩形Height和定义的偏移量,将矩阵中Width的当前位置乘以这些偏移量:( 请注意,索引用于乘以高度偏移量;当然与 相反)(x, y)xyprivate int[,] matrix = new int[3, 3] {&nbsp; &nbsp; { 0, 1, 0 },&nbsp; &nbsp; { 0, 1, 0 },&nbsp; &nbsp; { 0, 1, 1 }};Size rectSize = new Size(30, 30);private void aCanvas_Paint(object sender, PaintEventArgs e){&nbsp; &nbsp; int xPosition = 0;&nbsp; &nbsp; int yPosition = 0;&nbsp; &nbsp; using (var brush = new SolidBrush(Color.Tomato)) {&nbsp; &nbsp; &nbsp; &nbsp; for (var x = 0; x <= matrix.GetLength(0) - 1; x++)&nbsp; &nbsp; &nbsp; &nbsp; for (var y = 0; y <= matrix.GetLength(1) - 1; y++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; xPosition = y * rectSize.Width;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; yPosition = x * rectSize.Height;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (matrix[x, y] != 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var rect = new Rectangle(new Point(xPosition, yPosition), rectSize);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; e.Graphics.FillRectangle(brush, rect);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}使用此矩阵:private int[,] matrix = new int[3, 3] {&nbsp; &nbsp; { 0, 1, 0 },&nbsp; &nbsp; { 0, 1, 0 },&nbsp; &nbsp; { 1, 1, 1 }};你得到这个:
随时随地看视频慕课网APP
我要回答