有没有一种方法可以根据绘制文本时使用的drawText()方法返回要在Android canvas上绘制的文本的宽度(以像素为单位)?
发布于 2010-07-16 00:02:40
您看过android.graphics.Paint#measureText(String txt)(http://developer.android.com/reference/android/graphics/Paint.html#measureText(java.lang.String%29)?
发布于 2014-11-17 22:54:10
Paint paint = new Paint();
Rect bounds = new Rect();
int text_height = 0;
int text_width = 0;
paint.setTypeface(Typeface.DEFAULT);// your preference here
paint.setTextSize(25);// have this the same as your text size
String text = "Some random text";
paint.getTextBounds(text, 0, text.length(), bounds);
text_height =  bounds.height();
text_width =  bounds.width();发布于 2017-02-02 15:05:26
补充答案
Paint.measureText和Paint.getTextBounds返回的宽度略有不同。measureText返回一个宽度,其中包含字形的advanceX值,填充字符串的开头和结尾。getTextBounds返回的Rect宽度没有这种填充,因为边界是将文本紧密换行的Rect。
https://stackoverflow.com/questions/3257293
复制相似问题