Android中自定义控件获取text的宽高方式

来源:互联网 发布:win10有网络不能上网 编辑:程序博客网 时间:2024/04/27 02:33

paint = new Paint(Paint.ANTI_ALIAS_FLAG);

(1)获取高度方式

paint.setTextSize(subTitleTextSize);
        Paint.FontMetrics fm = paint.getFontMetrics();
        int textHeight = (int) Math.ceil(fm.descent - fm.ascent);


(2)获取宽度方式

  int width= paint.measureText(str)

  ②Rect rect = new Rect();

paint.getTextBounds(str, 0, str.length(), rect);

int w = rect.width(); //获取宽度

int h = rect.height();//获取高度

         ③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;

}

0 0
原创粉丝点击