要用Canvas绘制饼图,可以按照以下步骤进行:
<com.example.MyPieChartView
android:id="@+id/pie_chart"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true" />
public class MyPieChartView extends View {
private Paint paint;
private RectF rectF;
public MyPieChartView(Context context) {
super(context);
init();
}
public MyPieChartView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyPieChartView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
paint = new Paint();
paint.setAntiAlias(true);
rectF = new RectF();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 绘制饼图的数据
float[] data = {50, 30, 20};
// 饼图的中心点坐标
float centerX = getWidth() / 2f;
float centerY = getHeight() / 2f;
// 饼图的半径
float radius = Math.min(getWidth(), getHeight()) / 2f;
// 绘制饼图的区域
rectF.set(centerX - radius, centerY - radius, centerX + radius, centerY + radius);
float startAngle = 0;
for (float value : data) {
float sweepAngle = value / 100f * 360f;
// 设置每个区域的颜色
paint.setColor(getRandomColor());
// 绘制饼图的区域
canvas.drawArc(rectF, startAngle, sweepAngle, true, paint);
startAngle += sweepAngle;
}
}
private int getRandomColor() {
Random random = new Random();
return Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256));
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyPieChartView pieChartView = findViewById(R.id.pie_chart);
pieChartView.invalidate(); // 手动调用invalidate方法刷新View
}
}
通过以上步骤,就可以在Android中使用Canvas绘制饼图了。