Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate SpannableString witdh

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?

this is an example:

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());

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

Thanks

like image 933
vittochan Avatar asked Nov 22 '10 13:11

vittochan


1 Answers

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);
}

result:

measureTextWidth = 71.0
textWidth = 77.0

BoldText is wider.

like image 189
Yeung Avatar answered Oct 05 '22 19:10

Yeung