您的位置:首页 > 移动开发 > Android开发

Android基础之测量text宽度的三种方式

2016-05-12 23:06 531 查看
String str = "mare_blue";
canvas.drawText( str , x , y , paint);

//1. 粗略计算文字宽度
Log.d(TAG, "measureText=" + paint.measureText(str));

//2. 计算文字所在矩形,可以得到宽高
Rect rect = new Rect();
paint.getTextBounds(str, 0, str.length(), rect);
int w = rect.width();
int h = rect.height();
Log.d(TAG, "w=" +w+"  h="+h);

//3. 精确计算文字宽度
int textWidth = getTextWidth(paint, str);
Log.d(TAG, "textWidth=" + textWidth);

public static int getTextWidth(Paint paint, String str) {
int w= 0;
if (str != null && str.length() > 0) {
int len = str.length();
float[] widths = new float[len];
paint.getTextWidths(str, widths);
for (int j = 0; j < len; j++) {
w+= (int) Math.ceil(widths[j]);
}
}
return w;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: