测量文本问题的宽度

时间:2013-11-17 10:28:42

标签: android textview paint

我正在根据显示器的宽度计算文本的宽度。我将显示大小从像素(240x320)转换为dp(320x426)。很明显,Paint类测量文本会得到dp的结果。当我测量三个单词时通过下面给出的方法,它的结果超过320,但TextView在一行显示这些单词还有一些额外的空间???

private int calcWidthSize(CharSequence cha, int currentSize) {
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        return (int) Math.ceil(paint.measureText(cha, 0, cha.length()));
 } 

我尝试了另一种Paint方法,但问题仍未解决:

private int calculateWidthSize(CharSequence cha, int currentSize) {
        Rect bounds = new Rect();
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        paint.getTextBounds(cha.toString(), 0, cha.length(), bounds);
        return (int) Math.ceil(bounds.width());
 }

也许是TextView的错? 我的目标是测量文本的宽度和高度,我应该在textview(显示大小)中得到多少文本适合一页。请帮助。

1 个答案:

答案 0 :(得分:2)

在对我的代码进行一些更改后,我终于得到了解决方案:

private float calcWidthSize(CharSequence cha, float currentSize) {
        TextPaint paint = new TextPaint();
        paint.setTextSize(currentSize);
        return  paint.measureText(cha, 0, cha.length());
 }

currentSize之前直接设置,然后我通过从TextView获取textSize来提供currentSize参数,currentSize=tv.getTextSize();此外我没有将显示宽度转换为dp 。现在它返回中的结果像素 format.Hope它可以帮助某人...