以下是一个简单的自定义 View 实现圆饼不同扇形区域颜色的代码:

public class PieChartView extends View {

    private Paint mPaint;
    private List<Integer> mColors;
    private List<Float> mAngles;

    public PieChartView(Context context) {
        super(context);
        init();
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PieChartView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mColors = new ArrayList<>();
        mAngles = new ArrayList<>();
    }

    public void setColors(List<Integer> colors) {
        mColors = colors;
        invalidate();
    }

    public void setAngles(List<Float> angles) {
        mAngles = angles;
        invalidate();
    }

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

        if (mColors.size() != mAngles.size()) {
            return;
        }

        float totalAngle = 0;
        int width = getWidth();
        int height = getHeight();
        int radius = Math.min(width, height) / 2;

        RectF rectF = new RectF(width / 2 - radius, height / 2 - radius,
                width / 2 + radius, height / 2 + radius);

        for (int i = 0; i < mColors.size(); i++) {
            mPaint.setColor(mColors.get(i));

            float angle = mAngles.get(i);
            canvas.drawArc(rectF, totalAngle, angle, true, mPaint);

            totalAngle += angle;
        }
    }
}

使用方法:

  1. 在 XML 布局文件中添加 PieChartView:
<com.example.PieChartView
    android:id="@+id/pieChartView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
  1. 在 Java 代码中设置颜色和角度数据:
PieChartView pieChartView = findViewById(R.id.pieChartView);

List<Integer> colors = new ArrayList<>();
colors.add(Color.RED);
colors.add(Color.GREEN);
colors.add(Color.BLUE);

List<Float> angles = new ArrayList<>();
angles.add(120f);
angles.add(90f);
angles.add(150f);

pieChartView.setColors(colors);
pieChartView.setAngles(angles);

这样就可以根据设置的颜色和角度数据绘制出圆饼图了。

Android 自定义 View 实现圆饼图不同扇形区域颜色代码