1. 程式人生 > >自定義繪製一個扇形表

自定義繪製一個扇形表

 效果圖

/**
 * Created by lz on 2018/10/24.
 * 功能描述:扇形
 */

public class PieChat extends View {
    //Utils.dp2px   dp轉px
    private static final int RADIUS = (int) Utils.dp2px(150);
    private static final int LENGTH = (int) Utils.dp2px(20);
    private static final int PULLED_OUT_INDEX = 2;
    Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    //Rect的引數是  int型   ,  RectF的引數是float型,由此可以看出RectF比Rect的精確度更高。,他們都是通過四個座標引數來確定矩形的區域。
    RectF bounds = new RectF();
    int[] angles = {60, 100, 120, 80};
    int[] colors = {Color.parseColor("#2979FF"), Color.parseColor("#C2185B"),
        Color.parseColor("#009688"), Color.parseColor("#FF8F00")};
    public PieChat(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        bounds.set(getWidth()/2 - RADIUS,getHeight()/2-RADIUS,getWidth()/2+RADIUS,getHeight()/2+RADIUS);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int currentAngle = 0;
        for (int i=0;i<angles.length;i++){
            mPaint.setColor(colors[i]);
            canvas.save();
            if (i==PULLED_OUT_INDEX){
                canvas.translate((float) Math.cos(Math.toRadians(currentAngle + angles[i] / 2)) * LENGTH,
                    (float) Math.sin(Math.toRadians(currentAngle + angles[i] / 2)) * LENGTH);
            }
            canvas.drawArc(bounds,currentAngle,angles[i],true,mPaint);
            canvas.restore();
            currentAngle += angles[i];
        }
    }
}