- 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;
- }
Android drawText獲取text寬度的三種方式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.