Java And Anti-aliasing

Anti-aliasing is the processes of making the edges of lines on shapes or text less jagged. This is done by fooling the eye – intermediate pixels are added to smooth the color transition. So you might add some grey pixels between a black and a white point. It is very common in computer applications and games to make curves less jagged and text look crisper. Click here for some examples.

It is not something you generally need to worry about in Java because it is automatic. You draw a line and Java blends it into the display. What you can control in Java is whether it is used for drawing in Graphics2D. This is useful because while it is useful most of the time, on some occasions you do not want it enabled. If you have narrow sharp lines or you print low resolution images, it can make them look more blurry.

You control the Anti-aliasing by using Rendering Hints and applying them to the Graphics2D object you are drawing onto – this is nice because it means you can have different settings from Screen, image generation and printing. To create a RenderingHints, you use this code

hints =new RenderingHints(RenderingHints.KEY_RENDERING,
 RenderingHints.VALUE_RENDER_QUALITY);
hints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//hints.put(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);

You then enable it with

g2.setRenderingHints(hints);

If you would like to try it in our Java PDF library, we have added a call to allow users to control it in our printing routines. Here is how you can experiment with it. Can you see a difference?

/**
* print
*/
//before we do any print, allow user to alter hints
//customPrintHintingHandler implementes CustomPrintHintingHandler
//and passed in with PdfDecoder method
//addExternalHandler(MycustomPrintHintingHandlerImpementation,
Options.CustomPrintHintingHandler);

if (customPrintHintingHandler != null) {
   if(printRender != null) {
      printRender.stopG2HintSetting(true);
   }
   customPrintHintingHandler.preprint(g2,this);
}

Check out JPedal for more articles by Mark Stephens

Published
Categorized as Java

By Mark Stephens

Mark Stephens runs IDRsolutions, developing the JPedal PDF library in Java, and shares his thoughts on Java, PDF, the Business of Software and Mediaeval History at http://www.jpedal.org/PDFblog .