Android drawText獲取text寬度的三種方式

[java] view plaincopy
  1. String str = "Hello";  
  2. canvas.drawText( str , x , y , paint);  
  3.   
  4. //1. 粗略計算文字寬度  
  5. Log.d(TAG, "measureText=" + paint.measureText(str));  
  6.   
  7. //2. 計算文字所在矩形,可以得到寬高  
  8. Rect rect = new Rect();  
  9. paint.getTextBounds(str, 0, str.length(), rect);  
  10. int w = rect.width();  
  11. int h = rect.height();  
  12. Log.d(TAG, "w=" +w+"  h="+h);  
  13.   
  14. //3. 精確計算文字寬度  
  15. int textWidth = getTextWidth(paint, str);  
  16. Log.d(TAG, "textWidth=" + textWidth);  
  17.   
  18.     public static int getTextWidth(Paint paint, String str) {  
  19.         int iRet = 0;  
  20.         if (str != null && str.length() > 0) {  
  21.             int len = str.length();  
  22.             float[] widths = new float[len];  
  23.             paint.getTextWidths(str, widths);  
  24.             for (int j = 0; j < len; j++) {  
  25.                 iRet += (int) Math.ceil(widths[j]);  
  26.             }  
  27.         }  
  28.         return iRet;  
  29.     }  
發佈了21 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章