Stefan Berger
Stefan Berger

Reputation: 315

Java 2d drawString irregular letter spacing

enter image description here

Please have a close look at the image. This is how it was created:

BufferedImage ret = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g = ret.createGraphics();
Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>();
attributes.put(TextAttribute.TRACKING, -0.120F);
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
Font arial = new Font("Arial", Font.PLAIN, 10).deriveFont(attributes);
g.setFont(arial);
g.setColor(Color.BLUE);
g.drawString("Pumps", 0, 20);

My problem is the space between 'P' and 'u' compared to no space between 'u' and 'm'. The difference in the spaces between letters is not there in any text or image processing software. Am I doing it wrong? A quick research for alternative Java libraries with text drawing capabilities was unsuccessful.

Upvotes: 1

Views: 1420

Answers (1)

chiastic-security
chiastic-security

Reputation: 20520

The Javadoc for TextAttribute.TRACKING says:

The tracking value is multiplied by the font point size and passed through the font transform to determine an additional amount to add to the advance of each glyph cluster. Positive tracking values will inhibit formation of optional ligatures. Tracking values are typically between -0.1 and 0.3; values outside this range are generally not desireable.

You're pushing your luck slightly with -0.12.

But basically there's not much you can do if you're trying to draw text with so few pixels. It will always look bad if you zoom in to text drawn that small.

You ought to turn on subpixel rendering, though: that will make it look better, assuming you're on a screen that supports it. You've got greyscale at the moment.

Upvotes: 3

Related Questions