如何测量SpannableString高度?

时间:2015-08-05 19:15:39

标签: android text spannablestring

我有一个TextView,我在其中显示具有不同跨度大小的SpannableString。我需要知道SpannableString中最后一个单词的确切高度,但我使用的方法是错误的。我做错了什么?

这是我正在使用的测试代码

    SpannableStringBuilder spannableString = new SpannableStringBuilder("Some Text Some Text Some Text Some Text Some Text Some Text Some Text Some Text Some Text");
    spannableString.setSpan(new AbsoluteSizeSpan(10, true), 0, spannableString.length() / 3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new AbsoluteSizeSpan(15, true), spannableString.length()/3, 2 * spannableString.length()/3, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    spannableString.setSpan(new AbsoluteSizeSpan(20, true), 2 * spannableString.length() / 3, spannableString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    surfaceView.setTranslationY(measureSpannableHeight());

private int measureSpannableHeight() {
    StaticLayout staticLayout = new StaticLayout(spannableString, new TextPaint(), 480, Layout.Alignment.ALIGN_NORMAL, 1, 0, false);
    return staticLayout.getHeight();
}

(surfaceview的翻译仅用于说明测量方法的高度结果)

1 个答案:

答案 0 :(得分:0)

构造一个油漆对象,并在为油漆设置等效的跨度属性后,您可以使用以下方法测量您的字高。

Paint mTextPaint = new Paint();
mTextPaint.setTextSize(20) // your span size
mTextPaint.setTypeface(typeface)

单词的尺寸将保存在这个矩形中

Rect textBounds = new Rect();

int startIndex = spannableString.length() - 4; //length of your last word as start and end indices.
int endIndex = spannableString.length();
mTextPaint.getTextBounds(spannableString, startIndex, endIndex, textBounds); 

int height = textBounds.height();