Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficiently draw a grid in Windows Forms

I'm writing an implementation of Conway's Game of Life in C#. This is the code I'm using to draw the grid, it's in my panel_Paint event. g is the graphics context.

for (int y = 0; y < numOfCells * cellSize; y += cellSize)
{
     for (int x = 0; x < numOfCells * cellSize; x += cellSize)
     {
          g.DrawLine(p, x, 0, x, y + numOfCells * cellSize);
          g.DrawLine(p, 0, x, y + size * drawnGrid, x);
     }
}

When I run my program, it is unresponsive until it finishes drawing the grid, which takes a few seconds at numOfCells = 100 & cellSize = 10. Removing all the multiplication makes it faster, but not by very much.

Is there a better/more efficient way to draw my grid?

Thanks

like image 488
Joel Avatar asked May 02 '10 13:05

Joel


People also ask

How do I create a grid in Windows form?

Set global Windows Forms optionsIn Visual Studio, from the Tools menu, select Options. In the left pane of the Options dialog box, click Windows Forms Designer. In the right pane, under the Layout Settings heading, you can set the default grid settings for all the new forms you create.

How do you make a perfect grid on paper?

To draw the grid: Each square is 1 square inch. To draw this grid, put your ruler at the top of the paper, and make a small mark at every inch. Place the ruler at the bottom of the paper and do the same thing. Then use the ruler to make a straight line connecting each dot at the bottom with its partner at the top.

Which window is placed in the form of grid used to design a form?

Form Layout window is a simple visual basic design tool whose purpose is to give the user a thumbnail view of the current form. ...


2 Answers

You don't need nested loops :

for (int i = 0; i < numOfCells; i++)
{
    // Vertical
    g.DrawLine(p, i * cellSize, 0, i * cellSize, numOfCells * cellSize);
    // Horizontal
    g.DrawLine(p, 0, i * cellSize, numOfCells * cellSize, i * cellSize);
}
like image 115
Thomas Levesque Avatar answered Oct 19 '22 14:10

Thomas Levesque


The problem is that you are drawing the X lines for every Y coordinate. You can simplify first by just rendering the Y lines in one loop and then the X lines in another loop.

Here is a quick example

  for (int y = 0; y < numOfCells; ++y)
  {
    g.DrawLine(p, 0, y * cellSize, numOfCells * cellSize, y * cellSize);
  }

  for (int x = 0; x < numOfCells; ++x)
  {
    g.DrawLine(p, x * cellSize, 0, x * cellSize, numOfCells * cellSize);
  }

As you progress, you can use double buffering to reduce any flashing etc. Take a look at Control.SetStyle < br/> http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx

like image 41
Chris Taylor Avatar answered Oct 19 '22 12:10

Chris Taylor