前言:最近这段时间想根据网上博客的案例,自己练习自定义View,代码仅仅作为练习用,还有很多不足之处,见谅
案例取自:http://blog.csdn.net/wingichoy/article/details/50455412
先上传源码
public class PracticeView1 extends View {
private float mrectwidth = 200;
private float mrectheight = 100;
private float mround = 20;
private float len = 15;
private Paint mPaint = new Paint();
private Path mPath = new Path();
public PracticeView1(Context context) {
super(context);
}
public PracticeView1(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int mwidthmode = MeasureSpec.getMode(widthMeasureSpec);
int mwidthsize = MeasureSpec.getSize(widthMeasureSpec);
int mheightmode = MeasureSpec.getMode(heightMeasureSpec);
int mheightsize = MeasureSpec.getSize(heightMeasureSpec);
mrectwidth = (float) mwidthsize;
mrectheight = (float) mheightsize;
if(mwidthmode == MeasureSpec.AT_MOST) {
mrectwidth = (float) (600/2);
}
if(mheightmode == MeasureSpec.AT_MOST) {
mrectheight = (float) (300/2);
}
setMeasuredDimension((int) mrectwidth, (int) mrectheight);
Log.d("SunJ:", "mrectwidth " + String.valueOf(mrectwidth) + ", mrectheight " + String.valueOf(mrectheight));
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mPaint.setColor(Color.GRAY);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setAntiAlias(true);
RectF mRectF = new RectF(0, 0, mrectwidth, mrectheight-len);
canvas.drawRoundRect(mRectF, mround, mround, mPaint);
mPath.moveTo(mrectwidth/2, mrectheight);
mPath.lineTo(mrectwidth/2+len, mrectheight-len);
mPath.lineTo(mrectwidth/2-len, mrectheight-len);
mPath.close();
canvas.drawPath(mPath, mPaint);
}
}
效果图:
要点:
1.重写onMeasure()是为了在xml中设置layout_weight/layout_height属性为wrap_content时,不会变成match_parent
2.在onDraw()里面的矩形尺寸是由onMeasure()来得到的,这样子,在xml中设置具体的宽和高时,该矩形的大小同样也会发生相应的变化,这样,才能做到随意改变大小;而不会出现当设置具体的宽和高时,view缺胳膊少腿或者是多出空白的区域