使用Java Graphics.drawString替换完全合理化?
题
有没有人知道现有的代码可以让你在Java2D中绘制完全对齐的文本?
例如,如果我说, drawString(这里是“示例文本”,x,y,宽度)
,是否有一个现有的库可以找出该文本中有多少适合宽度,做一些字符间的间距,使文字看起来不错,并自动做基本的自动换行?
解决方案
虽然不是最优雅也不是最强大的解决方案,但这里的方法将采用 Font
。 html“rel =”noreferrer“> 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;
}
}
此实现将使用 String 分隔为 String
数组/docs/api/java/lang/String.html#split(java.lang.String)“rel =”noreferrer“> split
方法,空格字符作为唯一的单词分隔符,所以它可能不是很强大。它还假定该单词后跟一个空格字符,并在移动 curX
位置时相应地起作用。
如果我是你,我不建议使用这个实现,但是为了进行另一个实现所需的函数可能仍然使用 FontMetrics
class 。
其他提示
对于自动换行,您可能会感兴趣如何使用Graphics在多行上输出String 。这里没有理由,不确定是否容易(或不可能!)添加......
不隶属于 StackOverflow