1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
String str = "Hello";
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 iRet = 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++) {
iRet += (int) Math.ceil(widths[j]);
}
}
return iRet;
}

备注:如果要测量一段文字,要整体测量,不要单个字测量而后叠加,因为字与字有间距

来源:http://blog.csdn.net/chuekup/article/details/7518239