Use double buffering to prevent flicker when drawing graphics in C#

The example Draw a colored butterfly curve in C# shows how to draw a colorful butterfly curve. Without mentioning it, I used double buffering in that program to avoid flickering while drawing. To use double buffering, simply set a form's DoubleBuffer property to true.

When you use double buffering, the system allocates a separate piece of memory to holds the form's image. When the Paint event handler draws on the form, the system draws on this in-memory image. When it is finished, the system displays the form's image all at once. If the drawing is complicated, as in this example, that prevents the user from seeing the flickering image as the program draws.

When you check this example's checkbox, the program enables or disables double buffering and redraws. You can also click the Redraw button to force a redraw.
// Turn double buffering on or off.
private void chkDoubleBuffer_CheckedChanged(object sender,
 EventArgs e)
{
this.DoubleBuffered = chkDoubleBuffer.Checked;

// Redraw.
this.Invalidate();
}

// Redraw.
private void btnRedraw_Click(object sender, EventArgs e)
{
this.Invalidate();
}
When double buffering is off, you should see the flicker. When double buffering is on, the redraw happens so smoothly that you probably won't notice anything. Resize the form to force a redraw that is more noticeable.

Double buffering does take some extra memory so you should only use it when you will do enough drawing to make the flicker visible.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.