Android drawText获取text宽度的三种方式

来源:互联网 发布:软件flash是什么意思啊 编辑:程序博客网 时间:2024/06/02 03:06

转载自:http://blog.csdn.net/qin9r3y/article/details/8607014



[java] view plain copy
  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.     }  

0 0
原创粉丝点击