Search code examples
bufferbufferedimagejavax.imageioantialiasing

How to increase font quality on drawString method of Graphics?


In Paint XP or Paint Windows 8, when you write text, the program automatically increases the quality of the font (at least for fiscal printers). I would like to know how to do this with the same Java code below.

First, look at this image to see what I mean:

Text Quality Example

BufferedImage image = ImageIO.read(new File("blankdocument.bmp"));
Graphics g = ((BufferedImage) image).getGraphics();

Font helvetica = new Font("Lucida Sans Unicode", Font.PLAIN, 13);
g.setColor(Color.black);
g.setFont(helvetica);

g.drawString("TEXT WRITING EXAMPLE.", 5, 10);
ImageIO.write(image, "PNG", new File("testx.PNG"));
image.flush();

Solution

  • You can turn on anti-aliasing. From Controlling Rendering Quality,

    To set or change the rendering hints attribute in the Graphics2D context, construct a RenderingHints object and pass it into Graphics2D by using the setRenderingHints method. If you just want to set one hint, you can call Graphics2D setRenderingHint and specify the key-value pair for the hint you want to set. (The key-value pairs are defined in the RenderingHints class.)

    Graphics2D g2 = (Graphics2D) g;
    RenderingHints rh = new RenderingHints(RenderingHints.KEY_TEXT_ANTIALIASING,
                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHints(rh);