逐字符绘制文本时的字距调整问题
我正在尝试逐个字符地绘制字符串,以便为由文本组成的形状添加灯光效果。
while (i != line.length()) {
c = line.substring(i, i + 1);
cWidth = g.getFontMetrics().stringWidth(c);
g.drawString(c, xx += cWidth, yy);
i++;
}
问题是,当将这两个字符打印为字符串时,字符的宽度并不是与另一个字符绘制的实际距离。有什么方法可以在graphics2d中获得正确的距离吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Lukas Baran 的答案解决了可能导致输出看起来很糟糕的主要问题。然而,更微妙的问题仍然存在,即您无法以这种方式复制字距调整。这个问题的严重程度可能取决于您使用的字体。为了获得正确的字距调整,您可以执行以下操作:
这应该将每个字符放置在字距调整应放置的位置。
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:
That should place each character where the kerning would have placed it.
问题是字距调整定义了字母对的间距,并且逐个字符地迭代字符串使字距调整系统没有机会启动。我认为您必须使用固定宽度字体或重新设计您的灯光效果,使其适用于完整字符串而不是单个字符。
The problem is that kerning defines the spacing of pairs of letters, and iterating over a string char-by-char gives the kerning system no chance to kick in. I think you'll have to use either a fixed-width font or rework your lighting effect so it works with full strings instead of single chars.
我不确定我是否正确理解了你的问题。但是,我测试了您的代码,确实有些字符串字符相互重叠。
问题在于您递增 xx 值的方式(您在绘制字符之前递增它)。
这是代码的更正版本:
取消注释并调整
xx += 2
行以增加字符之间的间距。I'm not sure if I understood your problem correctly. However, I have tested your code and indeed some string characters overlapped each other.
The problem was in a way you're incrementing
xx
value (you were incrementing it before drawing a character).Here's corrected version of your code:
Uncomment and adjust
xx += 2
line to increase space between characters.