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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With