Android 关于自定义TextView的测量

1.在自定义的TextView 里如何得到文本控件的宽度

String mText = "测试";
int mTextSize = 30;
//使用画笔
Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
//设置文本大小
mPaint.setTextSize(mTextSize); 
private Rect mTextBound = new Rect();  
mPaint.getTextBounds(mText, 0, mText.length(), mTextBound);  
//得到文本宽度
int mTextWidth = (int) mPaint.measureText(mText);  

2.自定义的TextView ,如何测量文本的高度

private int measureHeight(int measureSpec)  {  
        int mode = MeasureSpec.getMode(measureSpec);  
        int val = MeasureSpec.getSize(measureSpec);  
        int height= 0;  
        switch (mode)   {  
        case MeasureSpec.EXACTLY:  
            height= val;  
            break;  
        case MeasureSpec.AT_MOST:  
        case MeasureSpec.UNSPECIFIED:  
            height= mTextBound.height();  
            break;  
        }  
        height= mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result;  
        return height+ getPaddingTop() + getPaddingBottom();  
    }  
3.如何测量文本的高度
    private int measureWidth(int measureSpec)  {  
        int mode = MeasureSpec.getMode(measureSpec);  
        int val = MeasureSpec.getSize(measureSpec);  
        int width= 0;  
        switch (mode)  {  
        case MeasureSpec.EXACTLY:  
            width= val;  
            break;  
        case MeasureSpec.AT_MOST:  
        case MeasureSpec.UNSPECIFIED:              
            width= mTextWidth;  
            break;  
        }  
        width= mode == MeasureSpec.AT_MOST ? Math.min(width, val) : width;  
        return width + getPaddingLeft() + getPaddingRight();  
    }  

你可能感兴趣的:(android,文本测量)