Calculate SpannableString witdh

╄→尐↘猪︶ㄣ 提交于 2019-12-18 12:14:12

问题


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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/4245809/calculate-spannablestring-witdh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!