Thursday, May 26, 2005

What is double buffering technique in Graphics?

Double Buffering is a technique that is used to prevent flicker when drawing onto the screen. The problem stems from the fact that when a new animation frame is rendered, it is desirable to first clear the old frame. This causes a flicker to occur. The basic idea of double buffering is to create a virtual screen out of the user's view. A graphics device could be a screen, printer, file, or memory area. The virtual screen used as the buffer is the primary example of using a memory space as a graphics device. When paint() is called, the clearing and painting of the animation frame can occur on the virtual screen and the resulting rendered image can then be transferred to the real screen immediately upon completion. The cost of double buffering is in memory and CPU consumption. However, this cost is probably unavoidable for complex animations and usually isn't too expensive.

A very good tutorial on how to reduce flicker in Java GUI applications is given at:
http://javaboutique.internet.com/tutorials/
Java_Game_Programming/BildschirmflackernEng.html

Excerpt from the article:

Double buffering means to paint all the things in the paint() method to an offscreen image. If all things that have to be painted, are painted, this image is copied to the applet screen. The method does the following in detail:

  • Generates a new offscreen-image by using createImage and stores this image in a instance variable( = generate an empty image)
  • Call getGraphics to get graphic context for this image
  • Draw everything (including to clear the screen completely) on the offscreen image ( = draw image in the background)
  • When finished, copy this image over the existing image on the screen. ( = draw image in the foreground)

This technique means that the picture is already painted before it is copied to the screen. When copying the image to the foreground the old pixels are overlayed by the new ones. There won't be any flickering picture anymore because there is not a millisecond where you see an empty screen!

The only disadvantage of the double buffering is, that it produces a large amount of data and every image is drawn two times (offscreen and when copying to the screen). But in most cases and on a fast computer this is much better than wasting time on finding an other solution!

No comments:

Post a Comment