本文讲述了Android使用自定义View实现饼状图的实例代码。分享给大家供大家参考,具体如下:
1.效果图
2.代码实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
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.使用:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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实现饼状图的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:https://blog.csdn.net/meetings/article/details/78871582