Effectively draw a grid in Windows Forms

I am writing a Conway Game of Life implementation in C #. This is the code I use to draw the grid 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 does not respond until it finishes drawing a grid, which takes a few seconds at numOfCells = 100 and cellSize = 10. Removing all multiplication does this faster, but not by much.

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

thanks

+4
source share
5 answers

The problem is that you draw X lines for each Y coordinate. First you can simplify by simply visualizing 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 move, you can use double buffering to reduce the number of blinks, etc. Take a look at Control.SetStyle http://msdn.microsoft.com/en-us/library/system.windows.forms.control.setstyle.aspx

+8
source

You do not 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); } 
+13
source

Create a bitmap of, say, 100x100 pixels with grid lines and display it in a tile.
Make sure that the seam between the plates does not cause a gap in the spaces of the mesh.

+1
source

You should take a look at XNA for this. It would probably be more efficient to do this in a rendered window instead of WinForm.

XNA is a gaming environment for C #. More information can be found at http://creators.xna.com/

0
source

I know it's late, but here ...

 for (int x = 0; x < 20; x++) { for (int y = 0; y < 20; y++) { g.drawRectangle(Pens.Black, x * 32, y * 32, 32, 32); } } 
0
source

Source: https://habr.com/ru/post/1308595/


All Articles