Home > Software design >  How can I draw a big image in WinForms?
How can I draw a big image in WinForms?

Time:12-14

I'm trying to make a floor for a top down style game, where I used to use pictureboxes

I was told that instead of using a Picturebox, I should be using the Graphics.DrawImage(); method, which seems to slightly help but still is very laggy.

My paint function looks like this to draw the background looks like this:

How should I make the drawing less laggy? The image is 2256 by 1504

private void Form1_Paint(object sender, PaintEventArgs e)
{
    Graphics g = e.Graphics;
    g.DrawImage(PeanutToTheDungeon.Properties.Resources.tutorialFloor, 0, 0);
}

CodePudding user response:

There are two points that I would make here.

Firstly, DO NOT use Properties.Resources like that. Every time you use a property of that object, the data for that resource gets extracted from the assembly. That means that you are creating a new Image object every time the Paint event is raised, which is often. You should use that resource property once and once only, assign the value to a field and then use that field repeatedly. That means that you will save the time of extracting that data and creating the Image object every time.

The second point may or may not be applicable but, if you are forcing the Paint event to be raised by calling Invalidate or Refresh then you need to make sure that you are invalidating the minimum area possible. If you call Refresh or Invalidate with no argument then you are invalidating the whole for, which means that the whole form will be repainted. The repainting of pixels on screen is actually the slow part of the process, so that's the part that you need to keep to a minimum. That means that, when something changes on your game board, you need to calculate the smallest area possible that will contain all the possible changes and specify that when calling Invalidate. That will reduce the amount of repainting and speed up the process.

Note that you don't need to change your drawing code. You always DRAW everything, then the system will PAINT the part of the form that you previously invalidated.

CodePudding user response:

After trying jmcilhinney's answer, by changing Properties.Resources to a single field and reusing it, instead of getting the image everytime, fixed all the lag.

  • Related