我正在运行时构建一个将放入TextView的文本.本文由不同大小的字体组成.我必须计算此文本的宽度(以像素为单位).我曾尝试使用Paint.measureText,但它没有考虑不同的字体大小.如何计算实际宽度?
这是一个例子:
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());
Run Code Online (Sandbox Code Playgroud)
在此示例中,如果我将相对大小设置为"2f"或"3f"(例如),则返回"MeasureText"的总大小是相同的.
谢谢
您可以使用它staticLayout.getLineWidth(line)
来计算SpannableString的宽度.例如:
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);
}
Run Code Online (Sandbox Code Playgroud)
结果:
measureTextWidth = 71.0
textWidth = 77.0
Run Code Online (Sandbox Code Playgroud)
BoldText更广泛.
Seb*_*oth -1
您可以使用 Paint.measureText,但需要正确设置它。这是我正在使用的:
// 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());
Run Code Online (Sandbox Code Playgroud)
BR
归档时间: |
|
查看次数: |
3451 次 |
最近记录: |