Last active
March 23, 2023 06:45
-
-
Save ongakuer/0ef96ebc7e89288590fd to your computer and use it in GitHub Desktop.
Android 测量字符宽度的几种方法和场景
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
mTextView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14); | |
TextPaint textPaint = mTextView.getPaint(); | |
String source = "Lorem ipsum dolor sit amet"; | |
// mTextView的宽度作为参考值 | |
mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() { | |
@Override | |
public void onGlobalLayout() { | |
int textViewWidth = mTextView.getMeasuredWidth(); | |
} | |
}); | |
/*----纯字符串测量----*/ | |
mTextView.setText(source); | |
// 1. measureText | |
float measureTextWidth = textPaint.measureText(source); | |
// 2. getTextBounds | |
Rect rect = new Rect(); | |
textPaint.getTextBounds(source, 0, source.length(), rect); | |
float rectWidth = rect.width(); | |
// 3. Layout.getDesiredWidth | |
float desiredWidth = Layout.getDesiredWidth(source, textPaint); | |
///////////////////////////////////// | |
// 1. measureTextWidth = 348.0 // | |
// 2. rectWidth = 346.0 // | |
// 3. desiredWidth = 347.7422 // | |
// 参考值: // | |
// textViewWidth = 348 // | |
///////////////////////////////////// | |
/*----包含Spanned字符测量----*/ | |
SpannableString sourceSpannable = new SpannableString(source); | |
sourceSpannable.setSpan(new RelativeSizeSpan(1.5F), 2, 4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); | |
mTextView.setText(sourceSpannable); | |
// 1. measureText 不适用 | |
// 2. getTextBounds 不适用 | |
// 3. Layout.getDesiredWidth 可以测量CharSequence | |
float spanDesiredWidth = Layout.getDesiredWidth(sourceSpannable, textPaint); | |
///////////////////////////////////// | |
// spanDesiredWidth = 359.61328 // | |
// 参考值: // | |
// textViewWidth = 360 // | |
///////////////////////////////////// | |
/*----TextPaint自定义后字符测量----*/ | |
textPaint.setFakeBoldText(true); //加粗 | |
textPaint.setTextSkewX(-0.5F); //斜体 | |
mTextView.setText(source); | |
// 1. measureText | |
float paintMeasureTextWidth = textPaint.measureText(source); | |
// 2. getTextBounds | |
Rect paintRect = new Rect(); | |
textPaint.getTextBounds(source, 0, source.length(), paintRect); | |
float paintRectWidth = paintRect.width(); | |
// 3. Layout.getDesiredWidth | |
float paintDesiredWidth = Layout.getDesiredWidth(source, textPaint); | |
////////////////////////////////////////// | |
// 1. paintMeasureTextWidth = 344.0 // | |
// 2. paintRectWidth = 351.0 // | |
// 3. paintDesiredWidth = 343.71094// | |
// 参考值: // | |
// textViewWidth = 344 // | |
////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment