Antialiasing

As we’ve already seen, you can request that Java 2D perform antialiasing when it draws text and graphics. Antialiasing smooths 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 discrete pixels. When the shape is drawn, the pixels inside the shape are filled, while the pixels outside are not. The outline of a shape rarely falls on perfect pixel boundaries, however, so approximations are made at the edges. The result is jagged lines that approximate the abstract shape you wish to represent.

Antialiasing is simply a technique for improving these approximations, using translucent colors. For example, if a pixel at the edge of a shape is half covered by the shape, the pixel is filled using a color that is half opaque. If only one-fifth of the pixel is covered, the pixel is one-fifth opaque. This technique works quite well to reduce jaggies. Figure 12-9 illustrates the process of antialiasing: it shows an antialiased figure that has been artificially enlarged to show the translucent colors used at the edges of shapes and text glyphs. The figure is generated by the straightforward code in Example 12-11.

Antialiasing enlarged

Figure 12-9. Antialiasing enlarged

Example 12-11. AntiAlias.java ...

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.