Java Reference
In-Depth Information
Example 11•16: GenericPaint.java (continued)
public ColorModel getColorModel() { return model; }
/**
* This is the main method of PaintContext. It must return a Raster
* that contains fill data for the specified rectangle. It creates a
* raster of the specified size, and loops through the device pixels.
* For each one, it converts the coordinates to user space, then calls
* the computeRed(), computeGreen() and computeBlue() methods to
* obtain the appropriate color for the device pixel.
**/
public Raster getRaster(int x, int y, int w, int h) {
WritableRaster raster = model.createCompatibleWritableRaster(w,h);
int[] colorComponents = new int[4];
for(int j = 0; j < h; j++) {
// Loop through rows of raster
int deviceY = y + j;
for(int i = 0; i < w; i++) { // Loop through columns
int deviceX = x + i;
// Convert device coordinate to user-space coordinate
double userX = origin.getX() +
deviceX * unitVectorX.getX() +
deviceY * unitVectorY.getX();
double userY = origin.getY() +
deviceX * unitVectorX.getY() +
deviceY * unitVectorY.getY();
// Compute the color components of the pixel
colorComponents[0] = computeRed(userX, userY);
colorComponents[1] = computeGreen(userX, userY);
colorComponents[2] = computeBlue(userX, userY);
colorComponents[3] = computeAlpha(userX, userY);
// Set the color of the pixel
raster.setPixel(i, j, colorComponents);
}
}
return raster;
}
/** Called when the PaintContext is no longer needed. */
public void dispose() {}
}
}
Advanced Animation
Way back in Example 11-4, we saw a simple animation technique that suffered,
unfortunately, from flickering. Example 11-17 is a program that performs a more
graphics-intensive animation but doesn't flicker, because it uses a technique
known as double-buffering : it draws each frame of the animation off-screen, then
copies the frame onto the screen all at once. This example also has better perfor-
mance because it requests redraws of only the relatively small portion of the
screen that needs to be redrawn.
Another interesting feature of this example is its use of the javax.swing.Timer
class to call the actionPerformed() method of a specified ActionListener object
at specified intervals. The Timer class is used here so that you don't have to create
Search WWH ::




Custom Search