Java Reference
In-Depth Information
Example 11•10: Paints.java (continued)
g.fill(shadowTransform.createTransformedShape(vshape));
// We're going to fill the next letter using a TexturePaint, which
// repeatedly tiles an image. The first step is to obtain the image.
// We could load it from an image file, but here we create it
// ourselves by drawing a into an off-screen image. Note that we use
// a GradientPaint to fill the off-screen image, so the fill pattern
// combines features of both Paint classes.
BufferedImage tile = // Create an image
new BufferedImage(50, 50, BufferedImage.TYPE_INT_RGB);
Graphics2D tg = tile.createGraphics(); // Get its Graphics for drawing
tg.setColor(Color.pink);
tg.fillRect(0, 0, 50, 50); // Fill tile background with pink
tg.setPaint(new GradientPaint(40, 0, Color.green, // diagonal gradient
0, 40, Color.gray)); // green to gray
tg.fillOval(5, 5, 40, 40);
// Draw a circle with this gradient
// Use this new tile to create a TexturePaint and fill the letter V
g.setPaint(new TexturePaint(tile, new Rectangle(0, 0, 50, 50)));
g.fill(vshape);
// Fill letter shape
g.setPaint(Color.black);
// Switch to solid black
g.draw(vshape);
// Draw outline of letter
// Move to the right and draw the shadow of the final A
g.translate(160, 0);
g.setPaint(shadowPaint);
g.fill(shadowTransform.createTransformedShape(ashape));
// For the last letter, use a custom Paint class to fill with a
// complex mathematically defined pattern. The GenericPaint
// class is defined later in the chapter.
g.setPaint(new GenericPaint() {
public int computeRed(double x, double y) { return 128; }
public int computeGreen(double x, double y) {
return (int)((Math.sin(x/7) + Math.cos(y/5) + 2)/4 *255);
}
public int computeBlue(double x, double y) {
return ((int)(x*y))%256;
}
public int computeAlpha(double x, double y) {
return ((int)x%25*8+50) + ((int)y%25*8+50);
}
});
g.fill(ashape);
// Fill letter A
g.setPaint(Color.black);
// Revert to solid black
g.draw(ashape);
// Draw the outline of the A
}
}
Antialiasing
As we've already seen, you can request that Java 2D perform antialiasing when it
draws text and graphics. Antialiasing smoothes the edges of shapes (such as text
glyphs) and lines and reduces jaggies. Antialiased drawing is necessary because
the outline of a shape drawn on a computer monitor can never be perfectly
smooth; a mathematically perfect shape can't be mapped precisely onto a grid of
Search WWH ::




Custom Search