Android使用自定义View实现饼状图的实例代码

作者:袖梨 2022-06-25

本文讲述了Android使用自定义View实现饼状图的实例代码。分享给大家供大家参考,具体如下:

1.效果图

2.代码实现

public class PieChartView extends View { 
 private Paint mPaint; 
 private ListpieDataList; 
 // 饼状图初始绘制角度 
 private float mStartAngle = 0; 
 public PieChartView(Context context) { 
 this(context, null); 
 } 
 public PieChartView(Context context, @Nullable AttributeSet attrs) { 
 super(context, attrs); 
 init(); 
 } 
 public void setData(List dataList){ 
 if (null == dataList || dataList.size() == 0) 
 return; 
 pieDataList = dataList; 
 invalidate(); //触发onDraw 
 } 
 private void init() { 
 mPaint = new Paint(); 
 mPaint.setAntiAlias(true); 
 mPaint.setStyle(Paint.Style.FILL); 
 mPaint.setStrokeWidth(4); 
 rectF = new RectF(100f, 100f, 600f, 600f); //正方形背景 
 } 
 private RectF rectF; 
 @Override 
 protected void onDraw(Canvas canvas) { 
 super.onDraw(canvas); 
 if (null == pieDataList || pieDataList.size() == 0) 
 return; 
 float currentAngle = mStartAngle; 
 for (int i = 0;i

3.使用:

int values[] = {30, 30, 40}; //右侧的图的数据,{10, 20, 70} 图左 
List pieDataList = new ArrayList<>(); 
PieData pieData1 = new PieData(); 
pieData1.percentage = (float) values[0] / 100; 
pieData1.angle = pieData1.percentage * 360; 
pieData1.color = Color.RED; 
pieDataList.add(pieData1); 
PieData pieData2 = new PieData(); 
pieData2.percentage = (float) values[1] / 100; 
pieData2.angle = pieData2.percentage * 360; 
pieData2.color = Color.GREEN; 
pieDataList.add(pieData2); 
PieData pieData3 = new PieData(); 
pieData3.percentage = (float) values[2] / 100; 
pieData3.angle = pieData3.percentage * 360; 
pieData3.color = Color.YELLOW; 
pieDataList.add(pieData3); 
 
PieChartView pieChartView = new PieChartView(mContext); 
pieChartView.setData(pieDataList); 
addView(pieChartView); 

相关文章

精彩推荐