【问题标题】:How to draw shapes using a 2D array to describe the shape?如何使用二维数组绘制形状来描述形状?
【发布时间】:2019-04-21 14:28:23
【问题描述】:

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

我正在尝试使用二维数组绘制 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)。你需要使用这种数组来绘制形状吗?通常,使用 Array/List 代替。也许,有一个GraphicsPath 类(没必要,很难)。
  • 用直线绘制形状的最简单方法是使用 DrawLines 或 FillPolygon。在您的情况下,您可能希望将每个元素视为一个像素。为此使用 Draw/FillRectangle 但使距离和大小相等,可能只需更改为 var rect = new Rectangle(x*30, y*30, 30, 30)
  • 天真的答案是您忘记将这些矩形的坐标相乘,new Rectangle(x, y ...,我想知道xy 有多高?你确定你没有忘记乘以 30? new Rectangle(x * 30, y * 30, ... ?

标签: c# arrays winforms graphics rectangles


【解决方案1】:

您当前的代码在稍微不同的位置(从(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 }
};

你明白了:

【讨论】:

  • 谢谢!这太棒了!希望我能一遍又一遍地投票。
猜你喜欢
  • 2012-07-04
  • 2010-10-27
  • 1970-01-01
  • 2012-07-09
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 2018-09-24
  • 2020-02-20
相关资源
最近更新 更多