要用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繪制餅圖了。