Manipulating and Displaying Images |
When a graphic is complex or the same graphic is used repeatedly, you can reduce the time it takes to display it by first rendering the graphic to an offscreen buffer and then copying the buffer to the screen. This technique, called double-buffering, is often used for animations.A
Note: When you are rendering into a Swing component, Swing automatically double-buffers the display.
BufferedImage
can easily be used as an offscreen buffer. You can create aBufferedImage
whose color space, depth, and pixel layout exactly match the window into which you're drawing by calling theComponent createImage
method. If you need control over the offscreen image's type or transparency, you can construct aBufferedImage
object directly and use it as an offscreen buffer.To draw into the buffered image, you call the
BufferedImage createGraphics
method to get aGraphics2D
object and then call the appropriate rendering methods on theGraphics2D
. All of the Java 2D API rendering features can be used when you're rendering to aBufferedImage
that's being used as an offscreen buffer.When you're ready to copy the
BufferedImage
to the screen, you simply calldrawImage
on your component'sGraphics2D
and pass in theBufferedImage
.Example: BufferedShapeMover
The
You can find the complete program inBufferedShapeMover
program allows the user to drag a rectangle around within the applet window. Instead of rendering the rectangle at every mouse location to provide feedback as the user drags it, aBufferedImage
is used as an offscreen buffer and theBufferedImage
is copied to each new mouse location as the rectangle is dragged.BufferedShapeMover.java
, and here's an HTML file that includes the applet,BufferedShapeMover.html
. Here is the code used to render into theBufferedImage
and blit the image to the screen:public void updateLocation(MouseEvent e){ rect.setLocation(last_x + e.getX(), last_y + e.getY()); repaint(); ... // In the update method... Dimension dim = getSize(); int w = dim.width; int h = dim.height; if(firstTime){ // Set up the offscreen buffer buffImg = (BufferedImage)createImage(w, h); big = buffImg.createGraphics(); rect.setLocation(w/2-50, h/2-25); firstTime = false; } else { ... // Clear the rectangle that was previously drawn. big.setColor(Color.white); big.clearRect(0, 0, w, h); big.setPaint(polkadots); // Render the rectangle into the buffered image. big.fill(rect); big.draw(rect); // Copy the buffered image to the screen. g2.drawImage(buffImg, 0, 0, this);
Manipulating and Displaying Images