View的测量

来源:互联网 发布:最新轰炸手机短信软件 编辑:程序博客网 时间:2024/05/02 02:50

MeasureSpec 测量view的类

  1. View的测量是在 onMeasure()方法中进行的,android 通过MeasureSpec来帮助我们测量。MeasureSpec是32位的int 值,其中高两位是 测量的模式,低 30位是测量的大小。
  2. 测量的模式有以下几种。

  1. EXACTLY 我们将控件的值设置为指定大小的时候,系统使用的是这个模式 如 layout_wrap = “20dp”
  2. AT_MOST 当控件的宽高指定为 wrap_content时,控件的大小随着内容的变化而变化的时候,此时控件的尺寸只要不超过父布局的大小即可。
  3. UNSPECIFIED 不指定大小模式,View想要到达就多大,通常在绘制自定义View时使用。
  4. 通过 MeasureSpec,我们就可以获取View的测量模式和View想要绘制的大小。
  5. 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);//指定该view的宽为  layout_wrap = "20dp" 或者 layout_match是成立        if(spcWidthModel == MeasureSpec.EXACTLY){            widthResult = width;        }else{            widthResult = 200;//该view默认的宽值            //该view的宽指定为  wrap_content时条件成立            if(spcWidthModel == MeasureSpec.AT_MOST){                widthResult = Math.min(width,widthResult);            }        }        if(spcHeightModel == MeasureSpec.EXACTLY){            heightResult =  height;        }else {            heightResult = 100;//该view默认的高值            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);//titleSize是通过自定义属性获取到的值         paint.getTextBounds(textCode,0,textCode.length(),mBound);         paint.setColor(textColor);//textColor是通过自定义属性获取到的值         canvas.drawText(textCode,widthResult / 2 - mBound.width() / 2, heightResult / 2 + mBound.height() / 2,paint);//widthResult 该View的宽     }
0 0
原创粉丝点击