计算 SpannableString witdh [英] Calculate SpannableString witdh

查看:16
本文介绍了计算 SpannableString witdh的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行时构建一个文本,该文本将被放入 TextView.该文本由不同大小的字体组成.我必须计算此文本的宽度(以像素为单位).我曾尝试使用 Paint.measureText,但它没有考虑不同的字体大小.如何计算实际宽度?

I'm building a text at runtime that will be put into a TextView. This text has composed with different size fonts. I must calculate the width in pixels of this text. I have tried to use Paint.measureText, but it does not consider the different font sizes. How can I calculate the real width?

这是一个例子:

LinearLayout text = (LinearLayout) findViewById(R.id.LinearLayout);

SpannableStringBuilder str = new SpannableStringBuilder("0123456789");
str.setSpan(new RelativeSizeSpan(2f), 3, 6, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

TextView tmp = new TextView(this);
tmp.setText(str,BufferType.SPANNABLE);
text.addView(tmp);

Float dim = tmp.getPaint().measureText(str, 0, str.length());

在本例中,如果我将相对大小设置为2f"或3f"(例如),则返回MeasureText"的总大小是相同的.

In this example, if I set the relative size to "2f " or "3f"(for example), the total size that returns "MeasureText" is the same.

谢谢

推荐答案

可以使用staticLayout.getLineWidth(line)来计算SpannableString的宽度.例如:

You can use staticLayout.getLineWidth(line) to calculate the width of SpannableString. For example:

CharSequence boldText = Html.fromHtml("<b>ABCDEFG</b>HIJK");
TextPaint paint = new TextPaint();

float measureTextWidth = paint.measureText(boldText, 0 , boldText.length());

StaticLayout tempLayout = new StaticLayout(boldText, paint, 10000, android.text.Layout.Alignment.ALIGN_NORMAL, 1f, 0f, false);
int lineCount = tempLayout.getLineCount();
float textWidth =0;
for(int i=0 ; i < lineCount ; i++){
    textWidth += tempLayout.getLineWidth(i);
}

结果:

measureTextWidth = 71.0
textWidth = 77.0

BoldText 更宽.

BoldText is wider.

这篇关于计算 SpannableString witdh的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆