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

在做自定义view事,看了这个方法,查找资料了解下,看到这篇文章不错,记录下!
http://blog.csdn.net/chuekup/article/details/7518239

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;  
        }  
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容