Ben Elo
Ben Elo

Reputation: 73

Making a grid of proceduraly generated squares in C#?

I'm workning on a project in C#, Windows form, and I require a grid of squares to do that. I have been able to generate the squares, but the problem is that I need to generate up to 20,736 of them. I was able to this in C++ without any issues using the SDL library, but in C# I am expierencing very bad lag with so many squares.

I want the squares to update every 1/100th of a second so I am using a timer to redraw the squares then, but the lag is incredible. I first tried to generate a grid of buttons, but the program just stopped. Then I tried a grid of PictureBoxes, imporvement, but not much, and then I tried Pen and Rectangle which yielded improvement too. So what is the most efficient way to draw 20,000 squares to the screen?

    //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();
    }

Upvotes: 1

Views: 2269

Answers (2)

Surfbutler
Surfbutler

Reputation: 1528

Instead of creating and disposing the Brush each time in editSquares, at startup create a brush for each color you need, then pass in the relevant brush as a parameter. Same goes for the Graphics object.

However, probably the best efficiency gain can be made by only redrawing those cells that have changed - thanks to Kal_Torak for pointing this out.

Upvotes: 1

Alex
Alex

Reputation: 266

Have you tried the answer detailed here?

The top answer is identical to how we do it at work. Our applications aren't super graphics intensive (so I'm not guaranteeing that our solution is optimal), but I think the writeable bitmap lock may prevent unnecessary error checking or screen updates.

Upvotes: 1

Related Questions