Friday, March 09, 2007

Implementing a Double Buffer

I recently had a project with the Motorola Q pulling data from a web service and displaying it in a graphical skin. I ran into a problem with flickering when painting the new changes using GDI+. To overcome this problem I set a Bitmap class up and painted to it then used the device graphics to paint the final image to the screen instead of painting to the screen directly. To accomplish this simply create the back image like so:

Bitmap _backBuffer = null;

private void Paint(object sender, PaintEventArgs e)
if (_backBuffer == null)
_backBuffer = new Bitmap(this.ClientSize.Width, this.ClientSize.Height);

using (Graphics g = Graphics.FromImage(_backBuffer))

// Do your stuff here like paint the back image and any text
g.DrawImage(MyImage, 0, 0);
g.DrawString("My Text", myFont, new SolidBrush(Color.Blue), myRectangleF);
} finally
e.Graphics.DrawImage(_backBuffer, 0, 0);

This will prevent the flicker and load images nicely. Also note when you make changes to the underlying dataset or collection or what ever you are using to hold the data you intend to paint make sure you call Invalidate to get the screen to paint again with the new changes.

Creative Commons License
Blogged Information and Code is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.