沒有辦法的東西要做到這一點,所以我也做它本人:
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;
}
}
這是固定寬度的字體嗎?否則,這將是非常棘手的。 – Thilo 2014-10-01 09:15:53
不,這是Arial, – TEXHIK 2014-10-01 09:17:14
請閱讀這裏:http://docs.oracle.com/javase/tutorial/2d/text/measuringtext.html – PeterMmm 2014-10-01 09:18:31