计算SpannableString witdh [英] Calculate 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屋!