Java Reference
In-Depth Information
Example 11•11: AntiAlias.java (continued)
// the background helps to demonstrate the anti-aliasing effect
ig.setPaint(new GradientPaint(0,0,Color.black,65,35,Color.white));
ig.fillRect(0, 0, 65, 35);
// Set drawing attributes for the foreground.
// Most importantly, turn on anti-aliasing.
ig.setStroke(new BasicStroke(2.0f)); // 2-pixel lines
ig.setFont(new Font("Serif", Font.BOLD, 18)); // 18-point font
ig.setRenderingHint(RenderingHints.KEY_ANTIALIASING, // Anti-alias!
RenderingHints.VALUE_ANTIALIAS_ON);
// Now draw pure blue text and a pure red oval
ig.setColor(Color.blue);
ig.drawString("Java", 9, 22);
ig.setColor(Color.red);
ig.drawOval(1, 1, 62, 32);
// Finally, scale the image by a factor of 10 and display it
// in the window. This will allow us to see the anti-aliased pixels
g.drawImage(image, AffineTransform.getScaleInstance(10, 10), c);
// Draw the image one more time at its original size, for comparison
g.drawImage(image, 0, 0, c);
}
}
Combining Colors with AlphaComposite
As I've just explained, antialiasing works by drawing with translucent colors at the
edges of a shape. But what exactly does it mean to draw with a translucent color?
Take another look at Figure 11-9, or, better yet, run the example using the Graph-
icsExampleFrame program, so you can see the example in full color. When you
draw with a translucent color, whatever color is below it “shows through.” In Fig-
ure 11-9, the background gray colors show through the pure translucent red and
blue colors, resulting in reddish and bluish grays. At the hardware level, of course,
there is no such thing as a translucent color; drawing with a translucent color is
simulated by combining the drawing color with the existing color beneath it.
Combining colors in this way is called compositing and is the job of the Composite
interface. You can pass a Composite object to the setComposite() method of a
Graphics2D object to tell it how to combine a drawing color (the source color)
with the colors that are already on the drawing surface (the destination colors).
Java 2D defines one implementation of the Composite interface, AlphaComposite ,
that combines colors based on their alpha transparency values.
The default AlphaComposite object used by Graphics2D is sufficient for most draw-
ing, so you don't often need to create AlphaComposite objects. Still, there are inter-
esting effects you can achieve with AlphaComposite . Example 11-12 demonstrates
these effects (and an unrelated clipping effect), which are shown in Figure 11-10.
The example does much of its drawing into an off-screen image, then copies the
contents of that image onto the screen. This is because many compositing effects
can only be achieved when working with a drawing surface (such as an off-screen
Search WWH ::




Custom Search