O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Combining Colors with AlphaComposite

As we’ve just seen, 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 12-9, or, better yet, run the example using the GraphicsExampleFrame 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 Figure 12-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 drawing, so you don’t often need to create AlphaComposite objects. Still, there are interesting effects you can achieve with AlphaComposite. Example 12-12 demonstrates these effects (and an unrelated ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required