BLOG.CSHARPHELPER.COM: Use double buffering to reduce flicker on a single PictureBox in C#
Use double buffering to reduce flicker on a single PictureBox in C#
The example Use double buffering to prevent flicker when drawing graphics in C# shows how to make a form use double-buffering to reduce flicker. Rather than drawing everything on the screen as it is generated, the form draws onto an image in memory and only displays the result when the image is complete.
But what if you only want to double-buffer for a PictureBox? The PictureBox control doesn't have a DoubleBuffered property as a form does.
Fortunately it's easy enough to provide double-buffering yourself. Simply create a Bitmap in memory and draw on it. When you're done, set the PictureBox's Image property to the Bitmap. Not only does this prevent flicker, but it also lets the PictureBox automatically redraw itself whenever necessary without you writing a Paint event handler.
With this technique, you should only need to recreate the Bitmap if the PictureBox changes size or the picture it shows must change.
The DrawCurves method shown in the following code draws this example's two butterfly curves. The PictureBox on the left uses double-buffering while the one on the right does not.
// Draw butterfly curves on both PictureBoxes. private void DrawCurves() { // Clear both images. picCanvas1.Image = null; picCanvas2.Refresh(); picCanvas1.Refresh();
int wid = picCanvas2.ClientSize.Width; int hgt = picCanvas2.ClientSize.Height;
// Draw with double-buffering. Bitmap bm = new Bitmap(wid, hgt); using (Graphics gr = Graphics.FromImage(bm)) { DrawButterfly(gr, wid, hgt); } picCanvas1.Image = bm; picCanvas1.Refresh();
// Draw without double-buffering. DrawButterfly(picCanvas2.CreateGraphics(), wid, hgt); }
The code first clears both PictureBoxes. Normally when you double-buffer you skip this step. Instead you simply create the new Bitmap and then display it, replacing whatever was displayed before.
Next the code creates a Bitmap and an associated Graphics object, and calls the DrawButterfly method to draw the butterfly curve on it. It sets the first PictureBox's Image property to the Biemap and refreshes it. In this example, you will see a brief flicker. If you don't clear the PictureBox, you won't notice a thing in this example.
The code finishes by calling DrawButterfly to draw a new butterfly curve on the second PictureBox. It uses a Graphics object for the PictureBox so the user sees the picture as the program draws it.
Comments