2008-12-30 89 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