Double Buffering

Team-Fly

Double buffering is a well-known technique for reducing flicker in drawing and animations. Imagine you are implementing an animation that clears and redraws the entire screen for each frame of the animation. Without double buffering, the animation will flicker badly as the screen is cleared and redrawn. With double buffering, the new frame is drawn into an off-screen image (the buffer). When the off-screen drawing is complete, the image is drawn on the screen in one smooth, quick move. You pay a price in the memory that's needed for the off-screen image, but the improvement in the quality of the animation is dramatic.

The MIDP implementation may provide double buffering by default. You can find out whether a Canvas is double buffered by calling the isDoubleBuffered() method.

If the implementation does not give you double buffering, you'll have to do it yourself. Fortunately, it's not terribly difficult. The process looks like this:

  1. Create an offscreen image by calling the static Image.createImage(int width, int height) method.

  2. Obtain a Graphics that draws into the image by calling getGraphics() on the Image.

  3. Draw stuff into the off-screen image using the Graphics object.

  4. In the paint() method of the Canvas, use drawImage() to put the off-screen image on the Canvas.

Here's a Canvas subclass that creates a simple off-screen image and displays it:

 import javax.microedition.lcdui.*; public class OffscreenCanvas     extends Canvas {   private Image mImage;   public void paint(Graphics g) {     if (mImage == null)       initialize();     g.drawImage(mImage, 0, 0, Graphics.TOP | Graphics.LEFT);   }   private void initialize() {     int w = getWidth();     int h = getHeight();     mImage = Image.createImage(w, h);     Graphics g = mImage.getGraphics();     g.drawRect(0, 0, w − 1, h − 1);     g.drawLine(0, 0, w − 1, h − 1);     g.drawLine(w − 1, 0, 0, h − 1);   } } 


Team-Fly


Wireless Java. Developing with J2ME
ColdFusion MX Professional Projects
ISBN: 1590590775
EAN: 2147483647
Year: 2000
Pages: 129

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net