Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kerning problems when drawing text character by character

I'm trying to draw strings character by character to add lighting effects to shapes composed of text.

while (i != line.length()) {
c = line.substring(i, i + 1);

cWidth = g.getFontMetrics().stringWidth(c);

g.drawString(c, xx += cWidth, yy);
i++;
}

The problem is, the width of a character isn't the actual distance it's drawn from another character when those two characters are printed as a string. Is there any way to get the correct distance in graphics2d?

like image 665
pkinsky Avatar asked Nov 05 '22 04:11

pkinsky


1 Answers

The answer by Lukas Baran solves the main problem that was probably causing your output to look bad. However, the more subtle problem that you can't replicate kerning in this way remains. How much of a problem this is may depend on the font you're using. To get the kerning right, too, you could do something like this:

while (i != line.length()) {
  String c = line.substring(i, i + 1);
  String d = line.substring(0, i + 1);
  int cWidth = g.getFontMetrics().stringWidth(c);
  int dWidth = g.getFontMetrics().stringWidth(d);
  g.drawString(c, xx + dWidth - cWidth, yy);
  i++;
}

That should place each character where the kerning would have placed it.

like image 152
joriki Avatar answered Nov 11 '22 05:11

joriki