2008-12-30 91 views
6

有谁知道现有的代码,可以让你在Java2D中绘制完全正确的文本?用Java Graphics.drawString替换完全对齐?

例如,如果我说drawString("sample text here", x, y, width),是否有一个现有的库可以计算出该文本中有多少符合该宽度,请执行一些字符间间距以使文本看起来很好,然后自动完成基本单词包装?

回答

17

虽然不是最优雅的,也没有强大的解决方案,下面是将当前Graphics对象的Font,并获得其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位置时相应地执行相应操作。

如果我是你,我不会推荐使用这个实现,但是为了使另一个实现仍然可以使用FontMetrics class提供的方法,可能需要这些函数。

+0

谢谢 - 我实际上开始研究类似的方法,并且我们的方法有许多相似之处。我还添加了一些可以调整字符间距的逻辑。 – 2008-12-30 16:27:54