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

时间:2021-05-20

本文讲述了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实现饼状图的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章