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 ...

Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.