一个动态饼图的自定义View实现

Talk is Cheap.

自定义View
public class ChartView extends View {
    // 视图宽高
    private int mWidth;
    private int mHeight;
    // 外圆环宽度
    private float outterStrokeWidth;
    // 内圆环宽度
    private float innerStrokeWidth;
    // 外圆矩形
    private RectF outterRect;
    // 内圆矩形
    private RectF innerRect;
    // 起始角度
    private float startAngle;
    // 角度数组
    private float[] angleArray;
    // 颜色数据
    private int[] outterColors;
    private int[] innerColors;
    // 某一时刻的覆盖角度
    private float coverAngle;
    // 动画时长
    private long duration = 3000;


    private Paint outterPaint;
    private Paint innerPaint;

    public ChartView(Context context) {
        super(context);
        initData();
        initPaint();
    }

    public ChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initData();
        initPaint();
    }

    /**
     * 初始化画笔
     */
    private void initPaint() {
        outterPaint = new Paint();
        outterPaint.setAntiAlias(true);
        outterPaint.setStyle(Paint.Style.STROKE);
        outterPaint.setStrokeWidth(outterStrokeWidth);

        innerPaint = new Paint();
        innerPaint.setAntiAlias(true);
        innerPaint.setStyle(Paint.Style.STROKE);
        innerPaint.setStrokeWidth(innerStrokeWidth);
    }

    /**
     * 初始化数据
     */
    private void initData(){
        outterStrokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
        innerStrokeWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, getResources().getDisplayMetrics());
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = w;
        mHeight = h;

        float halfOutterStrokeWidth = outterStrokeWidth / 2;
        outterRect = new RectF(halfOutterStrokeWidth, halfOutterStrokeWidth, mWidth - halfOutterStrokeWidth, mHeight - halfOutterStrokeWidth);
        float halfInnerStrokeWidth = innerStrokeWidth / 2;
        float temp = halfInnerStrokeWidth + outterStrokeWidth;
        innerRect = new RectF(temp, temp, mWidth - temp, mHeight - temp);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        drawByCoverAngle(canvas, coverAngle);
    }

    /**
     * 暴露接口
     * 传入数据和颜色
     */
    public void setDataAndColor(float[] datas, int[] outterColors, int[] innerColors) {
        if (datas == null || outterColors == null || innerColors == null) {
            throw new RuntimeException("数据不能为空");
        }

        if (datas.length != outterColors.length || datas.length != innerColors.length || outterColors.length != innerColors.length) {
            throw new RuntimeException("数据长度不匹配");
        }

        float sum = 0;
        for (int i = 0; i < datas.length; i++) {
            if (datas[i] < 0) {
                throw new RuntimeException("数据不能含负值:" + datas[i]);
            }
            sum += datas[i];
        }

        angleArray = new float[datas.length];
        for (int j = 0; j < datas.length; j++) {
            if (sum == 0) {
                angleArray[j] = 0;
            } else {
                angleArray[j] = (datas[j] / sum * 360);
            }
        }

        this.outterColors = outterColors;
        this.innerColors = innerColors;

        startAnim();
    }

    /**
     * 启动动画
     */
    private void startAnim() {
        new CountDownTimer(duration, 10) {

            @Override
            public void onTick(long millisUntilFinished) {
                float millis = duration - millisUntilFinished;
                coverAngle = millis / duration * 360;
                Log.e("TAG", "---->onTick coverAngle = " + coverAngle);
                invalidate();
            }

            @Override
            public void onFinish() {
                Log.e("TAG", "---->onFinish ");
                coverAngle = 360;
                invalidate();
            }
        }.start();
    }

    /**
     * 暴露接口
     * 传入起始角度
     */
    public void setStartAngle(float startAngle) {
        this.startAngle = startAngle;
    }

    /**
     * 根据覆盖角度进行绘制
     */
    private void drawByCoverAngle(Canvas canvas, float coverAngle) {
        Log.e("TAG", "drawByCoverAngle coverAngle:" + coverAngle);
        if (coverAngle <= 0 || coverAngle > 360) {
            return;
        }

        float angle = startAngle;
        for (int i = 0; i < angleArray.length; i++) {
            outterPaint.setColor(outterColors[i]);
            innerPaint.setColor(innerColors[i]);
            if (coverAngle >= angleArray[i]) {
                // 超过某一项
                canvas.drawArc(outterRect, angle - 0.5f, angleArray[i] + 0.5f, false, outterPaint);
                canvas.drawArc(innerRect, angle - 0.5f , angleArray[i] + 0.5f, false, innerPaint);
                coverAngle -= angleArray[i];
                angle += angleArray[i];
            } else {
                // 最后一项
                canvas.drawArc(outterRect, angle - 0.5f, coverAngle + 0.5f, false, outterPaint);
                canvas.drawArc(innerRect, angle - 0.5f, coverAngle + 0.5f, false, innerPaint);
                break;
            }
        }
    }
}

代码调用
public class MainActivity extends AppCompatActivity {
    private ChartView chartView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        chartView = (ChartView)findViewById(R.id.chartView);

        chartView.setStartAngle(-90);
        float[] datas = {20, 40, 90, 80, 70};
        int[] outterColors = {Color.parseColor("#CD5555"), Color.parseColor("#BA55D3"), Color.parseColor("#FFA500"), Color.parseColor("#3A5FCD"), Color.parseColor("#FFFF00")};
        int[] innerColors = {Color.parseColor("#8B3A3A"),Color.parseColor("#9932CC"), Color.parseColor("#FF8C00"), Color.parseColor("#27408B"), Color.parseColor("#FFD700")};
        chartView.setDataAndColor(datas, outterColors, innerColors);
    }
}

效果
一个动态饼图的自定义View实现_第1张图片
1.png
一个动态饼图的自定义View实现_第2张图片
2.png

你可能感兴趣的:(一个动态饼图的自定义View实现)