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;  
        }  
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容