先看看效果图
581.自定义 View 的基本流程
- 创建 View Class
- 创建 attr 属性文件,确定属性
- View Class 绑定 attr 属性
- onMeasure 测量
- onDraw 绘制
1.1 创建 View Class
public class ShapeView extends View {
public ShapeView(Context context) {
this(context, null);
}
public ShapeView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
1.2 创建 attr
<declare-styleable name="ShapeView">
<!--圆颜色-->
<attr name="circleColor" format="color"/>
<!--正方形颜色-->
<attr name="squareColor" format="color"/>
<!--三角形颜色-->
<attr name="triangleColor" format="color"/>
</declare-styleable>
1.3 绑定 attr
private void initAttr(Context context, AttributeSet attrs){
TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.ShapeView);
//圆颜色
circleColor = array.getColor(R.styleable.ShapeView_circleColor,circleColor);
//正方形颜色
squareColor = array.getColor(R.styleable.ShapeView_circleColor,squareColor);
//三角形颜色
triangleColor = array.getColor(R.styleable.ShapeView_circleColor,triangleColor);
//回收
array.recycle();
}
1.4 onMeasure
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//宽
int width = MeasureSpec.getSize(widthMeasureSpec);
//高
int height = MeasureSpec.getSize(heightMeasureSpec);
//设置宽高
setMeasuredDimension(Math.min(width, height), Math.min(width, height));
}
1.5 onDraw
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
switch (mShape) {
case CIRCLE:
//画圆形
int center = getWidth() / 2;
canvas.drawCircle(center, center, center, mCirclePaint);
break;
case SQUARE:
//画正方形
canvas.drawRect(0, 0, getWidth(), getHeight(), mSquarePaint);
break;
case TRIANGLE:
//画三角形
Path path = new Path();
path.moveTo(getWidth()/2, 0);
path.lineTo(0, (float) (getWidth() / 2 * Math.sqrt(3)));
path.lineTo(getWidth(), (float) (getWidth() / 2 * Math.sqrt(3)));
path.close();
canvas.drawPath(path, mTrianglePaint);
break;
}
}
onDraw 主要分为 3 个步骤,画圆、画正方形、画三角形
画圆和画正方形可以使用系统提供常用的 API
画等边三角形需要使用 drawPath 通过线去连接
给大家大致讲解一下画等边三角形的思路
等边三角形计算图形处理完成需要有个变化的方法
public void exchange() {
switch (mShape) {
case CIRCLE:
//正方形
mShape = Shape.SQUARE;
break;
case SQUARE:
//画三角形
mShape = Shape.TRIANGLE;
break;
case TRIANGLE:
//画圆形
mShape = Shape.CIRCLE;
break;
}
invalidate();
}
网友评论