如何计算字符串的宽度

Li *_*Che 2 android

可能重复:
如何在Android上获取字符串宽度?

我使用以下代码来计算字符串的宽度,但宽度的结果与TextView中显示的宽度有很大不同.我怎样才能正确地做到这一点?谢谢你的建议.

Paint paint= new Paint(); 
        paint.setTextSize(size);


        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;
Run Code Online (Sandbox Code Playgroud)

ckp*_*tel 5

我想尝试这个代码的宽度为字符串

float width = paint.measureText(string);
Run Code Online (Sandbox Code Playgroud)