However, after adding a grid to my map I noticed that it was running extremely slowly. It works fine when not drawing the grid but is very sluggish when I turn it on.
The tiles are 32x32 and I draw the grid in the picturebox's paint event as follows:
void mapEditorPicture_Paint(object sender, PaintEventArgs e) { // Draw the tiles e.Graphics.DrawImage(cursor, cursorMap.X * dimensions - 1, cursorMap.Y * dimensions - 1); if (tileMapPicture.Image != null) { // GraphicsUnit units = GraphicsUnit.World; //// RectangleF bmpRectangleF = tileMapPicture.Image.GetBounds(ref units); //// Rectangle bmpRectangle = Rectangle.Round(bmpRectangleF); e.Graphics.DrawImage(tileMapPicture.Image, new Rectangle(cursorMap.X * dimensions, cursorMap.Y * dimensions, dimensions, dimensions), new Rectangle(cursorTile.X * dimensions, cursorTile.Y * dimensions, dimensions, dimensions), GraphicsUnit.Pixel); } // Draw the grid if (mapGridCheck.Checked) { DrawGrid(mapEditorPicture.Size.Width, mapEditorPicture.Size.Height, e.Graphics); } }// Code for drawing the gridcells private void DrawGrid(int width, int height, Graphics graphics) { for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { Point point = new Point(dimensions * i, dimensions * j); graphics.DrawImage(gridCell, point); } } }
I'm guessing the problem is the thousands of iterations it must go through every time the paint method is called (3000 for a 100x30 grid). Am I using the paint event correctly?
Even when scrolling it seems to be extremely slow when the grid is on, telling me that it's repainting then too.
A couple of solutions that I've thought up are:
1. Only drawing a grid for the visible part of the picture, so instead of 3000 iterations, it might only be 300.
2. Drawing the grid in another picturebox on top of the first (sort of like a new layer), so that the only time it has to redraw the grid is when it is toggled on/off.
Is there a better way to go about this? Also, once I've got my tiles displaying properly, I'm guessing I'll run into the same problem. Is there am inbuilt way to get the paint event to redraw ONLY the parts of the screen that need redrawing? For example, if I place a tile at (0,0) it'll only redraw that single tile as everything else is unchanged? As well as only drawing what's actually displayed on the screen and not everything else? Or will I have to code it up myself?