在C#中制作程序生成的正方形网格?

时间:2012-07-26 21:44:57

标签: c# winforms

我正在使用C#,Windows窗体进行项目,我需要一个正方形网格才能做到这一点。我已经能够生成正方形,但问题是我需要生成多达20,736个正方形。我在C ++中能够使用SDL库时没有任何问题,但是在C#中我用很多方块来表示非常糟糕的延迟。

我希望方块每1/100秒更新一次,所以我使用计时器重新绘制正方形,但是滞后是不可思议的。我首先尝试生成一个按钮网格,但程序刚刚停止。然后我尝试了一个PictureBoxes网格,但是并没有多少,然后我尝试了Pen和Rectangle,这也产生了改进。那么在屏幕上绘制20,000个方格的最有效方法是什么?

    //Timer that ticks every 1/100th of a second 

    public void MyTimer_Tick(object sender,EventArgs eArgs)   {
          count++;
          numLabel.Text = count.ToString();
          for (int i = 0; i < 60; i++)
          {
              for (int j = 0; j < 60; j++)
              {
                  editSquares((i * (18 + 2)), (j * (18 + 2)), 18, 18, Color.Black);
              }
          }
    }

    //Draw a square

    public void drawSquares(int x, int y, int w, int h)
    {
        cell = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        System.Drawing.Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillRectangle(cell, new Rectangle(x, y, w, h));
        formGraphics.Dispose();
        cell.Dispose();
    }

    //Edit Squares      

    public void editSquares(int x, int y, int w, int h,Color color)
    {
        cell = new System.Drawing.SolidBrush(System.Drawing.Color.Red);
        cell.Color = color;
        System.Drawing.Graphics formGraphics = this.CreateGraphics();
        formGraphics.FillRectangle(cell, new Rectangle(x, y, w, h));
        cell.Dispose();
    }

2 个答案:

答案 0 :(得分:1)

不是每次在editSquares中创建和处理画笔,而是在启动时为您需要的每种颜色创建画笔,然后将相关画笔作为参数传递。图形对象也是如此。

然而,可能只有重新绘制已经发生变化的细胞才能获得最佳效率增益 - 感谢Kal_Torak指出这一点。

答案 1 :(得分:1)

您是否尝试过详细解答here?

最佳答案与我们在工作中的表现方式相同。我们的应用程序不是超级图形密集型(因此我不保证我们的解决方案是最佳的),但我认为可写位图锁可以防止不必要的错误检查或屏幕更新。