我们实现这样的效果,废话不多说,先看东西.
1 自定义属性
就这几个形状的颜色.
1.1 定义自定义属性
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ShapeView">
<!--圆形的颜色-->
<attr name="circleColor" format="color" />
<!--正方形的颜色-->
<attr name="squareColor" format="color" />
<!--三角形的颜色-->
<attr name="triangleColor" format="color" />
</declare-styleable>
</resources>
1.2 取出自定义属性
public ShapeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//自定义属性,圆的颜色,正方形的颜色,三角形的颜色
//获取自定义属性
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ShapeView);
mCircleColor = typedArray.getColor(R.styleable.ShapeView_circleColor, mCircleColor);
mSquareColor = typedArray.getColor(R.styleable.ShapeView_squareColor, mSquareColor);
mTriangleColor = typedArray.getColor(R.styleable.ShapeView_triangleColor, mTriangleColor);
//回收
typedArray.recycle();
}
2 onMeasure
确保是正方形即可.没有做特别处理.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//之确保是正方形即可
setMeasuredDimension(Math.min(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec))
, Math.min(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)));
}
3 onDraw()
@SuppressLint("DrawAllocation")
@Override
protected void onDraw(Canvas canvas) {
//判断当前的是什么形状就绘制什么形状
switch (mCurrentShape) {
case CIRCLE:
//绘制圆形
float cx = getWidth() / 2;
float cy = getWidth() / 2;
float radius = getWidth() / 2;
canvas.drawCircle(cx, cy, radius, mCirclePaint);
break;
case SQUARE:
//绘制正方形
if (mRect == null) {
mRect = new Rect(0, 0, getWidth(), getHeight());
}
canvas.drawRect(mRect, mSquarePaint);
break;
case TRIANGLE:
//绘制三角形,canvas没有直接绘制三角形的方法.只能通过绘制路径
if (mPath == null) {
mPath = new Path();
//等腰三角形
// mPath.moveTo(getWidth() / 2, 0);
// mPath.lineTo(0, getWidth());
// mPath.lineTo(getWidth(), getWidth());
// mPath.lineTo(getWidth() / 2, 0);
//改成等边三角形
mPath.moveTo(getWidth() / 2, 0);
mPath.lineTo(0, (float) (getWidth() / 2 * Math.sqrt(3)));
mPath.lineTo(getWidth(), (float) (getWidth() / 2 * Math.sqrt(3)));
mPath.close();//闭合路径
}
canvas.drawPath(mPath, mTrianglePaint);
break;
default:
break;
}
}
绘制圆形和正方形没有可说了.
绘制三角形,Canvas没有方法绘制三角形的.只能通过绘制路径来绘制三角形.
完整代码:shapeview