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.
Than开发者_运维百科ks
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.
You can use Paint.measureText, but you need to set it up properly. Here is what I'm using:
// init helper
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(1);
mPaint.setStrokeCap(Paint.Cap.ROUND);
// Measure
mPaint.setTextSize(mTextField1.getTextSize());
mPaint.setTypeface(mTextField1.getTypeface());
mText1TextWidth = mPaint.measureText(mTextField1.getText().toString());
BR
精彩评论