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:
Create an offscreen image by calling the static Image.createImage(int width, int height) method.
Obtain a Graphics that draws into the image by calling getGraphics() on the Image.
Draw stuff into the off-screen image using the Graphics object.
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 |