coo*_*ird 17
虽然不是最优雅也不是最强大的解决方案,但这里有一个方法可以获取Font
当前Graphics
对象并获取它FontMetrics
,以便找出绘制文本的位置,并在必要时移动到新行:
public void drawString(Graphics g, String s, int x, int y, int width)
{
// FontMetrics gives us information about the width,
// height, etc. of the current Graphics object's Font.
FontMetrics fm = g.getFontMetrics();
int lineHeight = fm.getHeight();
int curX = x;
int curY = y;
String[] words = s.split(" ");
for (String word : words)
{
// Find out thw width of the word.
int wordWidth = fm.stringWidth(word + " ");
// If text exceeds the width, then move to next line.
if (curX + wordWidth >= x + width)
{
curY += lineHeight;
curX = x;
}
g.drawString(word, curX, curY);
// Move over to the right for next word.
curX += wordWidth;
}
}
Run Code Online (Sandbox Code Playgroud)
此实现将使用带有空格字符的方法将给定String
的数组分离为唯一的单词分隔符,因此它可能不是非常健壮.它还假设该单词后跟空格字符,并在移动位置时相应地起作用.String
split
curX
如果我是你,我不建议使用这个实现,但是为了进行另一个实现所需的函数可能仍然使用FontMetrics
该类提供的方法.