使用Java Graphics.drawString替换完全合理化?

有没有人知道现有代码可以让你在Java2D中绘制完全对齐的文本?

例如,如果我说, drawString("sample text here", x, y, width) ,是否有一个现有的库可以找出该文本中有多少适合宽度,做一些字符间距来做文字看起来不错,并自动做基本的自动换行?

虽然不是最优雅也不是最强大的解决方案,但这里有一个方法,它将获取当前Graphics对象的FontMetrics并获取其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; } } 

此实现将使用split方法将给定的String分隔为String数组,并将空格字符作为唯一的单词分隔符,因此它可能不是很健壮。 它还假定该单词后跟空格字符,并在移动curX位置时相应地curX

如果我是你,我不建议使用这个实现,但是为了进行另一个实现,可能还需要使用FontMetrics类提供的方法。

对于自动换行,您可能会对如何使用Graphics在多行上输出String感兴趣。 这里没有理由,不确定是否容易(或不可能!)添加……