Search code examples
c#graphicsdoublebuffered

Should Double Buffering be done on a panel where I'm already drawing from a Bitmap, to minimize flicker?


I understand double buffering a panel basically means all the drawing is done to a buffer and then the buffer is copied directly to the drawing surface.
I am drawing to a Bitmap, and then drawing that Bitmap to my panel, using Graphics.DrawImage, so that I have the Bitmap saved and can make updates to it without having to re-do all the draw operations.
Is this the same as Double Buffering the panel, as far as the flickering of the panel is concerned? Or, should I be double buffering and re-doing all my drawing, if that means I will get lower flicker?
Edit: I am plotting points with DrawLine, the points are generated dynamically and I don't store a point once I am done plotting it. If I do Double Buffer, I will also have to incur the memory overhead of storing all the points I plot.


Solution

  • The optimal solution will mostly depend on what you draw, how many operations, how many pixels involved and the total size of the drawing surface.

    One common example is a drawing program, where the user piles strokes upon strokes, each consisting of hundreds of points..

    In general it is recommended to let the system take care of double-buffering the control you draw on. It will do a better job than you can hope for..

    So you should re-draw in the Paint event and not try to implement your own buffered bitmap drawing in order to get rid of flicker.

    The flicker will go away but with a huge number of drawing operations this will be slow and cause lags.

    To avoid lags you can combine the best of both methods:

    • draw the graphics until they get too many; it depends on the drawing calls (basically the number of pixels involved) and the speed of your system whether you can afford a few hundred or tens of thousands of drawing calls before you notice lags, say after N calls.

    • Then cache the first N drawing calls by drawing into a bitmap which you then set as the Panel's BackgroundImage. All drawing from N+1 will still be drawn onto the panel's surface in the Paint event. When you reach 2*N you create another version of the caching image, start surface drawing at 2*N+1 and so forth..