我目前正在尝试创建一个滚动文本方法,其中将采用String
. 很快,它将开始从左到右绘制,并随着时间的推移进入新的行,因此它不会从屏幕上绘制出来。我正在使用FontMetrics
来尝试实现我的目标。
我RollingText.render(Graphics g, int x, int y)
从我的主类中的渲染方法将参数传递给我。在我的render
方法中,我开始设置Graphics
字体和颜色,并抓取所有 . FontMetrics
,然后我开始从FontMetrics
. 同样,我进入一个用于将文本绘制到字符串的 for 循环。
public void render(Graphics g, int x, int y) {
// text is the field that a grab the index of the string from
// the index is the max part of the string I'm grabbing from,
// increments using the update() method
String str = text.substring(0, index);
String[] words = str.split(" ");
Font f = new Font(g.getFont().getName(), 0, 24);
FontMetrics fmetrics = g.getFontMetrics(f);
g.setColor(Color.white);
g.setFont(f);
int line = 1;
int charsDrawn = 0;
int wordsDrawn = 0;
int charWidth = fmetrics.charWidth('a');
int fontHeight = fmetrics.getHeight();
for (int i = 0; i < words.length; i++) {
int wordWidth = fmetrics.stringWidth(words[i]);
if (wordWidth* wordsDrawn + charWidth * charsDrawn > game.getWidth()) {
line++;
charsDrawn = 0;
wordsDrawn = 0;
}
g.drawString(words[i], x * charsDrawn + charWidth, y + fontHeight * line);
charsDrawn += words[i].length();
wordsDrawn += 1;
}
}
目前,此时一切都会正常工作,但留下的问题是drawString
方法中每个单词之间的空格被严重夸大了,如下所示:
该行:
g.drawString(words[i], x * charsDrawn + charWidth, y + fontHeight * line);
我目前遇到的唯一问题是找到正确的方法来计算 x 位置。目前,它的间距很大且动态取决于字长,我无法弄清楚如何让它看起来至少正常。我用我当前定义的整数尝试了不同的组合,等等。出现的问题包括不正确的间距、不恰当的定位和闪烁,以及一起运行的文本。
最后,我的问题是,将使用哪种算法来帮助我正确定位 x 坐标以使文本看起来正确?