Android笔记 自定义控件时drawText字符串宽度的3种计算方式

String str = "hello";
canvas.drawText(str, x, y, mPaint);

//1. 粗略计算文字宽度:
float width = mPaint.measureText(str);


//2. 计算文字的矩形,可以得到宽高:
Rect rect = new Rect();
mPaint.getTextBounds(str, 0, str.length(), rect);
int w = rect.width();
int h = rect.height();

//3. 精确计算文字的宽度:
public static int  getTextWidth(Paint mPaint, String str)
{
    float iSum = 0;
    if(str != null && !str.equals(""))
     {
           int len = str.length();
           float  widths[] = new float[len];
           paint.getTextWidths(str, widths);
           for(int i = 0; i < len; i++)
           {
                iSum += Math.ceil(widths[i])
           }
     }
     return (int)iSum;
}

你可能感兴趣的:(java,算法,开发语言)