Tuesday, July 29, 2008

Java: Images - BufferedImage

Java: Images - BufferedImage:

To create a BufferedImage

import java.awt.image.*;
. . .
class Painting extends JPanel {
. . .
BufferedImage grid; // declare the image
. . .
public void paintComponent(Graphics g) {
super.paintComponent(g); // paint background
Graphics2D g2 = (Graphics2D)g; // we need a Graphics2D context

if (grid == null) {
// Compute the grid only one time
int w = this.getWidth();
int h = this.getHeight();
grid = (BufferedImage)(this.createImage(w,h));
Graphics2D gc = grid.createGraphics();
for (int x=0; x<w; x+=10) {gc.drawLine(x, 0, x, h);}
for (int y=0; y<h; y+=10) {gc.drawLine(0, y, w, y);}
}
// Draw the grid from the precomputed image
g2.drawImage(grid, null, 0, 0);
. . . // draw remaining, dynamic, image

No comments:

Post a Comment