Android 中如何得到字符串的像素宽度。?
条件是:在不同字体,和不同大小的情况下都可以
字符串宽度可以这样:
Paint paint = new Paint();
float strWidth = paint.measureText(String);
paint.setTextSize(tv.getTextSize());
二.
private final Paint pFont = new Paint();
Rect rect = new Rect();
pFont.getTextBounds("小", 0, 1, rect);
Log.v(TAG, "height:"+rect.height()+"width:"+rect.width());
Paint mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mTextPaint.setColor(Color.WHITE);
// Define the string.
String displayText = “Hello World!”;
// Measure the width of the text string.
float textWidth = mTextPaint.measureText(displayText);
Paint mPaint = new Paint();
mPaint.setTextSize(16);
float FontSpace = mPaint.getFontSpacing();
return text.length()*FontSpace;
最后的结果 用字符串长度 × 字体宽度。得到字符长度最接近实际长度,但是当出现英文或者是标点符号时,长度就会缩小