| Animation by Example:
Using an Offscreen to Eliminate Flicker by David Matuszek |
Flicker occurs because you are trying to change the display at the same time your computer is trying to show you the display. The secret is to get the display ready first, then give the computer the new, completed display.
Instead of painting onto the same Graphics g that the computer
is using, create a new, "offscreen" Graphics, do your
work there, and move it to g when it's all painted and ready to
be seen. This technique is also called double buffering.
Double buffering can be done completely in the update() method,
as follows:
// These are declared in the View class, so we don't have
// to construct them every time we enter the update() method
Image offscreenImage = null;
Graphics offscreenGraphics = null;
/**
* To avoid flicker, this method paints into the Graphics
* of an offscreen Image.
*/
public void update(Graphics g) {
Image offscreenImage = null;
Graphics offscreenGraphics = null;
// Create the offscreen Graphics
if (offscreenImage == null) {
offscreenImage = createImage(getSize().width, getSize().height);
offscreenGraphics = offscreenImage.getGraphics();
}
// Paint into the offscreen Graphics
background(offscreenGraphics);
paint(offscreenGraphics);
// Copy the offscreen onto the screen
g.drawImage(offscreenImage, 0, 0, null);
}
The result should be a stable, flicker-free image.![]() |
|
|
|
|