Search code examples
c#winformsgraphicsdrawingtile

Preventing System.Drawing.Graphics from updating


I'm creating a 2D game engine that uses a tile system. When it is drawing these tiles, you can see each one be individually drawn on the screen. It's very fast with drawing but you can still see it.

When I tell the graphics to draw something, I do not want it to update immediately because it has other things to draw on the screen and is obviously very inefficient. I want it to still "draw" what I tell it, but then actually show it all in one big update...Or would that do the exact same thing? Probably not possible anyway.

//Creating graphics
public static Form GameForm; //Assigned by the form
public static Graphics GFX;

public static void Init()
{
  GFX = GameForm.CreateGraphics();
  GameForm.BackColor = Color.Black;

  // ----

  //Drawing the tiles
  while (X != 480)
  {
    while (Y != 352)
    {
      Tiles.Add(new Tile(X, Y, Num, 0));

       GFX.DrawImage(LoadedImages[4], new Point(X, Y));
       GFX.DrawRectangle(new Pen(Color.Red), X, Y, 32, 32);
       GFX.DrawString(Num.ToString(), new Font("System", 10.0F),
                                      new SolidBrush(Color.Black),
                                      new PointF((float)X, (float)Y));

        Y = Y + 32;
        Num++;
      }
      X = X + 32;
      Y = 0;
    }
    //UPDATE NOW!

Solution

  • Create a bitmap that's the same size as the screen. Then call Graphics.FromImage to get a Graphics object instance that you can draw on. Draw everything into that object. When you're done, copy the temporary bitmap to the screen with Graphics.DrawImage.

    That is:

    // Create bitmap
    using (var bmp = new Bitmap(form_width, form_height, GFX))
    {
        using (var g = Graphics.FromImage(bmp))
        {
            // do all your drawing to g
        }
    
        // draw bmp to GFX
        GFX.DrawImage(bmp, 0, 0);
    }