String str = "Hello";
canvas.drawText( str , x , y , paint);
//1. 粗略計(jì)算文字寬度
Log.d(TAG, "measureText=" + paint.measureText(str));
//2. 計(jì)算文字所在矩形祖秒,可以得到寬高
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. 精確計(jì)算文字寬度
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;
}
Paint類measureText與getTextBounds的區(qū)別
在使用Canvas繪制文字時(shí)诞吱,需要得到字符串的長(zhǎng)度,Paint類內(nèi)給了兩個(gè)方法竭缝,measureText()房维,getTextBound();
可是對(duì)于同于字符串兩個(gè)方法得出來(lái)的值有些差別:
getTextBounds() 得到的寬度總是比 measureText() 得到的寬度要小一點(diǎn)。
就查看方法的源碼
getTextBounds():
measureText():
額抬纸,只能看出兩種方法測(cè)量的方式不一樣咙俩,getTextBounds()使用了nativeGetCharArrayBounds();measureText()使用了native_measureText().
然而并不能解決疑問(wèn),就上網(wǎng)搜湿故。運(yùn)氣不錯(cuò)阿趁,有位大神詳細(xì)的回答了膜蛔。
下面貼出重點(diǎn):
This is font size 60, in red is bounds rectangle, in purple is result of measureText.
It's seen that bounds left part starts some pixels from left, and value of measureText is incremented by this value on both left and right.
最后總結(jié)下:measureText()是計(jì)算出來(lái)的寬度是包含了內(nèi)邊距的,但是getTextBounds()這個(gè)方法計(jì)算的結(jié)果是不包含內(nèi)邊距的脖阵,只是計(jì)算這個(gè)文字包裹的矩形的寬高包含在矩形里面
原文鏈接:http://blog.csdn.net/lyndsc/article/details/51556508
上篇原文鏈接:http://blog.csdn.net/qin9r3y/article/details/8607014