Archive

Posts Tagged ‘interpolation’

Quick hit – antialiasing in Java Graphics2D

February 9, 2010 8 comments

If you’re trying to use antialiasing in Java, chances are you’ll do some searching and come to the conclusion that you have to set the rendering hints for the Graphics object in order to eliminate your jaggies. Probably like so:

Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);

And you’ll probably wonder why your graphics are still jagged. That’s because you haven’t instructed Java what type of interpolation to use for the antialiasing; by default you’ll get Nearest Neighbor, which is fast but won’t get you far in the image department. You can instead choose to use bilinear interpolation (slower) or bicubic interpolation (slowest).

Here’s how to enable the alternate interpolation modes:

Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);

or

g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC)

You make a trade off between speed and image quality; to my eyes bilinear looks fine. Compare for yourself:

Thanks to Chris Cambpell’s blog for showing me this.

Advertisements