1.View测量
如果我们要想绘制一个图形,首先我们要知道这个图形的大小;再是这个图形具体在什么位置;最后将图形绘制出来。
- onMeasure()
如果我们想知道这个图形的大小,必须通过onMeasure()方法来发帮助我们测量View,MeasureSpec是以个32位的int值,其中高2位为测量模式,低30为测量的大小,在计算中使用位运算原因是为了提高并优化效率。
测量的模式有以下三种
- EXACTLY
即精确值模式,当我们的控件的layout_width属性或layout_height属性指定为match_parent(占据父View的大小) 或者 android:layout_width=”100dp”,系统使用的是EXACTLY- AT_MOST
即最大值模式,当我们的控件的layout_width属性或layout_height属性指定为warp_content时,控件大小随着控件的子控件或内容的变化而变化,此时控件的尺寸只要不超过父控件语序的最大尺寸即可。- UNSPECIFIED
它不指定其大小测量模式,View想多大就多大,通常情况下在绘制自定义View时才会使用。View类默认的onMeasure()方法只支持EXACTLY模式,如果要让自定义View支持wrap_content属性,那么就必须重写onMeasure()方法来指定wrap_content时大小。
代码如下
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// super.onMeasure(widthMeasureSpec, widthMeasureSpec);
//第一步,从MeasureSpec对象中提取出具体的测量模式和大小
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
int measuredHeight, measuredWidth;
if (widthMode == MeasureSpec.EXACTLY) { //精确值模式
measuredWidth = widthSize;
} else {
measuredWidth = SIZE;
}
if (heightMode == MeasureSpec.EXACTLY) {
measuredHeight = heightSize;
} else {
measuredHeight = SIZE;
}
setMeasuredDimension(measuredWidth, measuredHeight);
}