- 继承View重写onDraw的同时,还需要注意2点
- 1.该控件在布局中用wrap_content的时候
- 2.该控件用padding的时候
- 问题一:如果用了wrap_content则需要重写onMeasure方法!进行判断
private int mHeight = 200;
private int mWidth = 200;
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width_mode = MeasureSpec.getMode(widthMeasureSpec);
int width_size = MeasureSpec.getSize(widthMeasureSpec);
int height_mode = MeasureSpec.getMode(heightMeasureSpec);
int height_size = MeasureSpec.getSize(heightMeasureSpec);
if (width_mode == MeasureSpec.AT_MOST && height_mode == MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth , mHeight);
}else if (width_mode == MeasureSpec.AT_MOST ){
setMeasuredDimension(mWidth , height_size);
}else if (height_mode == MeasureSpec.AT_MOST ){
setMeasuredDimension(width_size , mHeight);
}
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int paddingBottom = getPaddingBottom();
int paddingLeft = getPaddingLeft();
int paddingRight = getPaddingRight();
int paddingTop = getPaddingTop();
int width = getWidth()-paddingLeft - paddingRight;
int height = getHeight()-paddingTop - paddingBottom;
int radius = Math.min(width, height) / 2;
canvas.drawCircle(width/2 + paddingLeft, height/2 + paddingTop, radius , mPaint);
}
<xingao.com.ui.CircleView
android:id="@+id/cv_view"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:padding="10dp"
/>