2012-12-21 48 views
1

我在尋找是否可以在給定Example中添加高度元素。如何在圖像上附加文字時添加高度元素

,這樣我可以指定

public void drawString(Graphics g, String s, int x, int y, int width,int height) 

現在,如果我的文字超過其高度下次上的文字重疊。

+0

你到底想幹什麼? – maloney

+0

你想繪製佔據多個行的字符串..? – Sorceror

+0

我正在繪製佔據多行的字符串。但是如果最後一行超過指定的高度,我想限制字符串。 –

回答

0

我沒有測試,但可能會幫助你解決問題..

public void drawString(Graphics g, String s, int x, int y, int width, int height) { 
    // 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; 
    int totalHeight = 0; 

    String[] words = s.split(" "); 

    String word = ""; 
    // end of words array wasn't reached and still some space left 
    for(int i = 0; i < words.length && totalHeight <= height; i++) { 

     // 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; 
      totalHeight += lineHeight; 
      curX = x; 
     } 

     g.drawString(word, curX, curY); 

     // Move over to the right for next word. 
     curX += wordWidth; 
    } 
}