2014-10-01 60 views
-1

我有一個文本字符串,有關字體和行寬度的信息(以像素爲單位)。是否有可能計算,有多少行將採取此字符串。計數,多少行將給定文本字符串

If a word is long, it will be writen in a next row, for example: 
some test string | 
very_very_long_word | 

and even if there will be many white space 

so very_very_long_word <= this can't be on one row 
so     | 
very_very_long_word | 

and if the word is too long, it will be separated at the end of row: 
veryveryverylonglong| 
word    | 
+0

這是固定寬度的字體嗎?否則,這將是非常棘手的。 – Thilo 2014-10-01 09:15:53

+0

不,這是Arial, – TEXHIK 2014-10-01 09:17:14

+0

請閱讀這裏:http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html – PeterMmm 2014-10-01 09:18:31

回答

0

你可以使用不同的類

與Graphics2D的

FontRenderContext frc = ((Graphics2D)g).getFontRenderContext(); 
String s = range.displayName; 
float textWidth = (float) font.getStringBounds(s, frc).getWidth(); 
float textHeight = (float) font.getStringBounds(s, frc).getHeight(); 

或者只是使用的FontMetrics

FontMetrics fm = c.getFontMetrics(font); 
int fontHeight = fm.getHeight(); 
int w = fm.stringWidth("yourstring"); 
+0

這將給我的字符串的寬度,但正如我所說,如果例如,我有一個30像素的行,35像素的單詞將在30像素分離,但是:3 15像素的單詞將需要3個字符串,而不是2! – TEXHIK 2014-10-01 09:31:21

0

沒有辦法的東西要做到這一點,所以我也做它本人:

public class LineCalculator { 

private static final FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true); 
private static Font font; 
private static int lines; 

public int calcLines(String str, int width, String fontFamily, int scale) 
{ 
    font = new Font(fontFamily, Font.PLAIN, scale); 
    String[] source = str.split(" "); 
    String line = ""; 
    lines = 1; 

    for (int i = 0; i < source.length - 1; i++) { 
     source[i] += " "; 
    } 

    for (String word : source) { 
     if (font.getStringBounds(line + word, frc).getWidth() > width) { 
      lines++; 
      line = singleWordCheck(word, width); 
     } 
     line += word; 
    } 
    return lines; 
} 

private String singleWordCheck(String str, int width) 
{ 
    CharSequence chars = str; 
    for (int i = 1; i < chars.length(); i++) { 
     if (font.getStringBounds(chars.subSequence(0, i).toString(), frc).getWidth() > width) { 
      lines++; 
      return singleWordCheck(chars.subSequence(i, chars.length() - 1).toString(), width); 
     } 
    } 
    return str; 
} 

}

相關問題