我們實(shí)現(xiàn)這樣的效果,廢話不多說,先看東西.
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) {
//判斷當(dāng)前的是什么形狀就繪制什么形狀
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