MeasureSpec 测量view的类
- View的测量是在 onMeasure()方法中进行的,android 通过MeasureSpec来帮助我们测量。MeasureSpec是32位的int 值,其中高两位是 测量的模式,低 30位是测量的大小。
- 测量的模式有以下几种。
- EXACTLY 我们将控件的值设置为指定大小的时候,系统使用的是这个模式 如 layout_wrap = “20dp”
- AT_MOST 当控件的宽高指定为 wrap_content时,控件的大小随着内容的变化而变化的时候,此时控件的尺寸只要不超过父布局的大小即可。
- UNSPECIFIED 不指定大小模式,View想要到达就多大,通常在绘制自定义View时使用。
- 通过 MeasureSpec,我们就可以获取View的测量模式和View想要绘制的大小。
- onMeasure()方法的模板代码
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
widthResult = 0;
heightResult = 0;
int width = MeasureSpec.getSize(widthMeasureSpec);
int spcWidthModel = MeasureSpec.getMode(widthMeasureSpec);
int height = MeasureSpec.getSize(heightMeasureSpec);
int spcHeightModel = MeasureSpec.getMode(heightMeasureSpec);
if(spcWidthModel == MeasureSpec.EXACTLY){
widthResult = width;
}else{
widthResult = 200;
if(spcWidthModel == MeasureSpec.AT_MOST){
widthResult = Math.min(width,widthResult);
}
}
if(spcHeightModel == MeasureSpec.EXACTLY){
heightResult = height;
}else {
heightResult = 100;
if(spcHeightModel == MeasureSpec.AT_MOST){
heightResult = Math.min(height,heightResult);
Log.d("TestCodeView","spcHeightModel == MeasureSpec.AT_MOST ---"+ heightResult+"\n"+ height);
}
}
setMeasuredDimension(width, height);
}
- 然后就可以复写 onDraw()方法。canvas对象来绘制需要的图形了。这里绘制了矩形,在并在矩形中绘制了文字,该矩形的尺寸就是该view尺寸
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas)
paint = new Paint()
paint.setStrokeWidth(frameStrokeWidth)
paint.setColor(Color.BLACK)
paint.setStyle(Paint.Style.STROKE)
Log.v("TestCodeView","widthResult "+ widthResult +"\n"+ "heightResult "+heightResult)
canvas.drawRect(0,0,widthResult,heightResult,paint)
Rect mBound = new Rect()
paint.setTextSize(titleSize)
paint.getTextBounds(textCode,0,textCode.length(),mBound)
paint.setColor(textColor)
canvas.drawText(textCode,widthResult / 2 - mBound.width() / 2, heightResult / 2 + mBound.height() / 2,paint)
}