算一下,给定文本字符串需要多少行

时间:2014-10-01 09:13:09

标签: java string-formatting

我有一个文本字符串,有关字体和行宽的信息,以像素为单位。是否有可能计算出该字符串需要多少行。

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                |

2 个答案:

答案 0 :(得分:0)

你可以使用不同的类

with 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");

答案 1 :(得分: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;
}

}

相关问题