当前位置 : 主页 > 手机开发 > android >

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

来源:互联网 收集:自由互联 发布时间:2021-06-05
本文讲述了Android使用自定义View实现饼状图的实例代码。分享给大家供大家参考,具体如下: 1.效果图 2.代码实现 public class PieChartView extends View { private Paint mPaint; private ListPieDatapieDataL

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

1.效果图


2.代码实现

public class PieChartView extends View { 
 private Paint mPaint; 
 private List<PieData>pieDataList; 
 // 饼状图初始绘制角度 
 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<PieData> 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<pieDataList.size();i++){ 
 PieData pieData = pieDataList.get(i); 
 mPaint.setColor(pieData.color); 
 canvas.drawArc(rectF,currentAngle,pieData.angle,true,mPaint); //画弧 
 currentAngle += pieData.angle; 
 } 
 } 
} 

3.使用:

int values[] = {30, 30, 40}; //右侧的图的数据,{10, 20, 70} 图左 
List<PieData> 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); 

以上所述是小编给大家介绍的Android使用自定义View实现饼状图的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对自由互联网站的支持!

网友评论