Julian Schaefer
Julian Schaefer

Reputation: 37

c#:WindowsForms - performance optimization when redrawing bitmap

In my program I have a picture box, containing a bitmap.(300x300 35kB .PNG file)

If 2 variables(x/z coord) are changed, I draw a new circle every second to the new position accordingly - a timer runs in the background, invoking this method.

void DrawEllipse()
{       
  // Retrieve the image.
  bChamber = new Bitmap(global::Project.Properties.Resources.driveChamber1);

  gChamber = Graphics.FromImage(bChamber);
  gChamber.FillEllipse(brushChamber, VirtualViewX(), VirtualViewY(), 10, 10);
  pictureBoxDriveView.Image = bChamber;        
}

Now I'm looking for ways to optimize the performance. Redrawing the pic every 0.2s e.g. slows the program so much, I cant do anything else. But ultimately I need a more fluent movement of the circle, you can Imagine how it laggs with the 1000ms refresh rate.

Is there a better way to do this, then loading the whole bitmap every time?

Upvotes: 0

Views: 965

Answers (4)

Henk Holterman
Henk Holterman

Reputation: 273244

Use the Controls the way they were intended.

  • do not redraw the Bitmap yourself.
  • just load it 1x in the Picturebox.
  • handle the Paint event of the picturebox to draw the ellipse
  • invalidate the Picturebox whenever your coords change.

Upvotes: 2

Jurgen Camilleri
Jurgen Camilleri

Reputation: 3589

Try setting the DoubleBuffered property of the form to true. This generally results in improved performance.

Also, you should put this

// Retrieve the image.
bChamber = new Bitmap(global::Project.Properties.Resources.driveChamber1);

In the class constructor.

Upvotes: 0

mtsiakiris
mtsiakiris

Reputation: 190

Try this, it does not load the image from disk every time, so it is less expensive.

private Image _origImage = new Bitmap(global::Project.Properties.Resources.driveChamber1);

void DrawEllipse()
{
    // Retrieve the image.
    Image bChamber = new Bitmap((Image)this._origImage.Clone());

    Graphics gChamber = Graphics.FromImage(bChamber);

    gChamber.FillEllipse(brushChamber, VirtualViewX(), VirtualViewY(), 10, 10);
    pictureBoxDriveView.Image = bChamber;
}

Upvotes: -1

Emond
Emond

Reputation: 50672

Draw the circle ONE time in a control (PictureBox)

Put the control across the 300x300 picture box.

When, and only when, the variables change, update the location of the picturebox with the circle.

This way you prevent drawing too many times.

Upvotes: 0

Related Questions