Aswin Balaji

Aswin Balaji

186 Sadasivam Nagar,Madipakkam,Chennai, TN 600091
Aswin Balaji

CREATING PIECHART VIEW IN ANDROID

June 18, 2016, by Aswinbalaji, category ANDROID

Piechart is a graph that display datas in circle and then diplays the percentage of those datas, While android does not provide built-in view for pie view ( as I know), so we have to use the third party View to display pie chart. In this project I do not create the PiewView widget from scratch by my own, I download the code from GitHub (https://github.com/HackPlan/AndroidCharts). In this project I just show how to implement PiewView in a minimum (simple) way for beginners. The Image below shows the result of this project after you run it.
Piechart View Android

First of all create a new android application project in Eclipse. and then in the activity_main.xml write this xml code:
activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
    xmlns:tools=”http://schemas.android.com/tools”
    android:layout_width=”match_parent”
    android:layout_height=”match_parent”
    android:paddingBottom=”@dimen/activity_vertical_margin”
    android:paddingLeft=”@dimen/activity_horizontal_margin”
    android:paddingRight=”@dimen/activity_horizontal_margin”
    android:paddingTop=”@dimen/activity_vertical_margin”
    tools:context=”com.abanxdroid.pieview.MainActivity” >
    <com.abanxdroid.pieview.PieView
        android:layout_width=”300dp”
        android:layout_height=”wrap_content”
        android:id=”@+id/pieView”/>
</RelativeLayout>

and then create a new java class (PieView.java), this is the class that I downloaded from GitHub.
PieView.java

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package com.abanxdroid.pieview;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* Created by Dacer on 9/26/14.
*/
public class PieView extends View {
    public interface OnPieClickListener{
        void onPieClick(int index);
    }
    private Paint cirPaint;
    private Paint whiteLinePaint;
    private Point pieCenterPoint;
    private Paint textPaint;
    private RectF cirRect;
    private RectF cirSelectedRect;
    private int mViewWidth;
    private int mViewHeight;
    private int margin;
    private int pieRadius;
    private OnPieClickListener onPieClickListener;
    private ArrayList<PieHelper> pieHelperList;
    private int selectedIndex = NO_SELECTED_INDEX;
    private boolean showPercentLabel = true;
    public static final int NO_SELECTED_INDEX = -999;
    private final int[] DEFAULT_COLOR_LIST = {Color.parseColor(“#33B5E5”),
            Color.parseColor(“#AA66CC”),
            Color.parseColor(“#99CC00”),
            Color.parseColor(“#FFBB33”),
            Color.parseColor(“#FF4444”)};
    private Runnable animator = new Runnable() {
        @Override
        public void run() {
            boolean needNewFrame = false;
            for(PieHelper pie : pieHelperList){
                pie.update();
                if(!pie.isAtRest()){
                    needNewFrame = true;
                }
            }
            if (needNewFrame) {
                postDelayed(this, 10);
            }
            invalidate();
        }
    };
    public PieView(Context context){
        this(context,null);
    }
    public PieView(Context context, AttributeSet attrs){
        super(context, attrs);
        pieHelperList = new ArrayList<PieHelper>();
        cirPaint = new Paint();
        cirPaint.setAntiAlias(true);
        cirPaint.setColor(Color.GRAY);
        whiteLinePaint = new Paint(cirPaint);
        whiteLinePaint.setColor(Color.WHITE);
        whiteLinePaint.setStrokeWidth(2f);
        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(MyUtils.sp2px(getContext(), 13));
        textPaint.setStrokeWidth(5);
        textPaint.setTextAlign(Paint.Align.CENTER);
        pieCenterPoint = new Point();
        cirRect = new RectF();
        cirSelectedRect = new RectF();
    }
    public void showPercentLabel(boolean show){
        showPercentLabel = show;
        postInvalidate();
    }
    public void setOnPieClickListener(OnPieClickListener listener){
        onPieClickListener = listener;
    }
    public void setDate(ArrayList<PieHelper> helperList){
        initPies(helperList);
        pieHelperList.clear();
        removeSelectedPie();
        if(helperList != null && !helperList.isEmpty()){
            for(PieHelper pieHelper:helperList){
                pieHelperList.add(new PieHelper(pieHelper.getStartDegree(),pieHelper.getStartDegree(),pieHelper));
            }
        }else {
            pieHelperList.clear();
        }
        removeCallbacks(animator);
        post(animator);
//        pieHelperList = helperList;
//        postInvalidate();
    }
    /**
     * Set startDegree and endDegree for each PieHelper
     * @param helperList
     */
    private void initPies(ArrayList<PieHelper> helperList){
        float totalAngel = 270;
        for(PieHelper pie:helperList){
            pie.setDegree(totalAngel, totalAngel + pie.getSweep());
            totalAngel += pie.getSweep();
        }
    }
    public void selectedPie(int index){
        selectedIndex = index;
        if(onPieClickListener!=null) onPieClickListener.onPieClick(index);
        postInvalidate();
    }
    public void removeSelectedPie(){
        selectedIndex = NO_SELECTED_INDEX;
        if(onPieClickListener!=null) onPieClickListener.onPieClick(NO_SELECTED_INDEX);
        postInvalidate();
    }
    @Override
    protected void onDraw(Canvas canvas) {
        if(pieHelperList.isEmpty()){
            return ;
        }
        int index = 0;
        for(PieHelper pieHelper : pieHelperList){
            boolean selected = (selectedIndex == index);
            RectF rect = selected? cirSelectedRect: cirRect;
            if(pieHelper.isColorSetted()){
                cirPaint.setColor(pieHelper.getColor());
            }else {
                cirPaint.setColor(DEFAULT_COLOR_LIST[index%5]);
            }
            canvas.drawArc(rect, pieHelper.getStartDegree(), pieHelper.getSweep(), true, cirPaint);
            drawPercentText(canvas, pieHelper);
            drawLineBesideCir(canvas, pieHelper.getStartDegree(), selected);
            drawLineBesideCir(canvas, pieHelper.getEndDegree(), selected);
            index++;
        }
    }
    private void drawLineBesideCir(Canvas canvas, float angel, boolean selectedCir){
        int sth2 = selectedCir? mViewHeight/2 : pieRadius; // Sorry I’m really don’t know how to name the variable..
        int sth = 1;                                       // And it’s
        if(angel%360 > 180 && angel%360 < 360){
            sth = -1;
        }
        float lineToX = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * sth2);
        float lineToY = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * sth2);
        canvas.drawLine(pieCenterPoint.x, pieCenterPoint.y, lineToX, lineToY, whiteLinePaint);
    }
    private void drawPercentText(Canvas canvas, PieHelper pieHelper){
        if(!showPercentLabel) return ;
        float angel = (pieHelper.getStartDegree() + pieHelper.getEndDegree()) /2;
        int sth = 1;
        if(angel%360 > 180 && angel%360 < 360){
            sth = -1;
        }
        float x = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * pieRadius/2);
        float y = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * pieRadius/2);
        canvas.drawText(pieHelper.getPercentStr(), x, y, textPaint);
    }
    private void drawText(Canvas canvas, PieHelper pieHelper){
        if(pieHelper.getTitle() == null) return ;
        float angel = (pieHelper.getStartDegree() + pieHelper.getEndDegree()) /2;
        int sth = 1;
        if(angel%360 > 180 && angel%360 < 360){
            sth = -1;
        }
        float x = (float)(mViewHeight/2 + Math.cos(Math.toRadians(-angel)) * pieRadius/2);
        float y = (float)(mViewHeight/2 + sth * Math.abs(Math.sin(Math.toRadians(-angel))) * pieRadius/2);
        canvas.drawText(pieHelper.getTitle(), x, y, textPaint);
    }
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN ||event.getAction() == MotionEvent.ACTION_MOVE){
            selectedIndex = findPointAt((int) event.getX(), (int) event.getY());
            if(onPieClickListener != null){
                onPieClickListener.onPieClick(selectedIndex);
            }
            postInvalidate();
        }
        return true;
    }
    /**
     * find pie index where point is
     * @param x
     * @param y
     * @return
     */
    private int findPointAt(int x, int y){
        double degree = Math.atan2(x-pieCenterPoint.x, y-pieCenterPoint.y)* 180 / Math.PI;
        degree = -(degree-180) + 270;
        int index = 0;
        for(PieHelper pieHelper:pieHelperList){
            if(degree>=pieHelper.getStartDegree() && degree<=pieHelper.getEndDegree()){
                return index;
            }
            index++;
        }
        return NO_SELECTED_INDEX;
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mViewWidth = measureWidth(widthMeasureSpec);
        mViewHeight = measureHeight(heightMeasureSpec);
        margin = mViewWidth/16;
        pieRadius = (mViewWidth)/2-margin;
        pieCenterPoint.set(pieRadius+margin, pieRadius+margin);
        cirRect.set(pieCenterPoint.x-pieRadius,
                pieCenterPoint.y-pieRadius,
                pieCenterPoint.x+pieRadius,
                pieCenterPoint.y+pieRadius);
        cirSelectedRect.set(2, //minor margin for bigger circle
                2,
                mViewWidth-2,
                mViewHeight-2);
        setMeasuredDimension(mViewWidth, mViewHeight);
    }
    private int measureWidth(int measureSpec){
        int preferred = 3;
        return getMeasurement(measureSpec, preferred);
    }
    private int measureHeight(int measureSpec){
        int preferred = mViewWidth;
        return getMeasurement(measureSpec, preferred);
    }
    private int getMeasurement(int measureSpec, int preferred){
        int specSize = View.MeasureSpec.getSize(measureSpec);
        int measurement;
        switch(View.MeasureSpec.getMode(measureSpec)){
            case View.MeasureSpec.EXACTLY:
                measurement = specSize;
                break;
            case View.MeasureSpec.AT_MOST:
                measurement = Math.min(preferred, specSize);
                break;
            default:
                measurement = preferred;
                break;
        }
        return measurement;
    }
}

Next, create a new java class (PieHelper.java), this the class that I downloaded from GitHub.
PieHelper.java

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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package com.abanxdroid.pieview;
import android.graphics.Color;
/**
* Created by Dacer on 11/14/13.
*/
public class PieHelper {
    private float startDegree;
    private float endDegree;
    private float targetStartDegree;
    private float targetEndDegree;
    private String title;
    private int color;
    private float sweepDegree;
    int velocity = 5;
    /**
     *
     * @param percent from 0 to 100
     */
    public PieHelper(float percent){
        this(percent, null, 0);
    }
    public PieHelper(float percent, int color){
        this(percent, null, color);
    }
    /**
     *
     * @param percent from 0 to 100
     * @param title
     */
    PieHelper(float percent, String title){
        this(percent, title, 0);
    }
    /**
     *
     * @param percent from 0 to 100
     * @param title
     * @param color
     */
    PieHelper(float percent, String title, int color){
        this.sweepDegree = percent * 360 / 100;
        this.title = title;
        this.color = color;
    }
    PieHelper(float startDegree, float endDegree, PieHelper targetPie){
        this.startDegree = startDegree;
        this.endDegree = endDegree;
        targetStartDegree = targetPie.getStartDegree();
        targetEndDegree = targetPie.getEndDegree();
        this.sweepDegree = targetPie.getSweep();
        this.title = targetPie.getTitle();
        this.color = targetPie.getColor();
    }
    PieHelper setTarget(PieHelper targetPie){
        this.targetStartDegree = targetPie.getStartDegree();
        this.targetEndDegree = targetPie.getEndDegree();
        this.title = targetPie.getTitle();
        this.color = targetPie.getColor();
        this.sweepDegree = targetPie.getSweep();
        return this;
    }
    void setDegree(float startDegree, float endDegree){
        this.startDegree = startDegree;
        this.endDegree = endDegree;
    }
    boolean isColorSetted(){return color != 0;}
    boolean isAtRest(){
        return (startDegree==targetStartDegree)&&(endDegree==targetEndDegree);
    }
    void update(){
        this.startDegree = updateSelf(startDegree, targetStartDegree, velocity);
        this.endDegree = updateSelf(endDegree, targetEndDegree, velocity);
        this.sweepDegree = endDegree – startDegree;
    }
    String getPercentStr(){
        float percent = sweepDegree / 360 * 100;
        return String.valueOf((int)percent) + “%”;
    }
    public int getColor(){ return color; }
    public String getTitle(){
        return title;
    }
    public float getSweep(){
        return sweepDegree;
    }
    public float getStartDegree(){
        return startDegree;
    }
    public float getEndDegree(){
        return endDegree;
    }
    private float updateSelf(float origin, float target, int velocity){
        if (origin < target) {
            origin += velocity;
        } else if (origin > target){
            origin-= velocity;
        }
        if(Math.abs(target-origin)<velocity){
            origin = target;
        }
        return origin;
    }
}

Next, create a new java class (MyUtils.java), this is the class that I downloaded from GitHub.
MyUtils.java

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
package com.abanxdroid.pieview;
import android.content.Context;
/**
* Created by Dacer on 10/8/13.
*/
public class MyUtils {
    public static int dip2px(Context context, float dipValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(dipValue * scale + 0.5f);
    }
    public static int px2dip(Context context, float pxValue){
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int)(pxValue / scale + 0.5f);
    }
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}

Then,, finally in the MainActivity.java, write this java code.
MainActivity.java

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
41
42
43
44
45
46
47
package com.abanxdroid.pieview;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
public class MainActivity extends Activity {
private ArrayList<PieHelper> dataList;
private PieView pie_view;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        pie_view = (PieView) this.findViewById(R.id.pieView);
        dataList = new ArrayList<PieHelper>();
        // create data1 for 10%
        PieHelper data1 = new PieHelper(10, “data1”);
        // add to arrayList
        dataList.add(data1);
        // create data2 for 22%
        PieHelper data2 = new PieHelper(22, “data2”);
        dataList.add(data2);
        // create data3 for 30%
        PieHelper data3 = new PieHelper(30, “data3”);
        dataList.add(data3);
        // create data4 for 35%
        PieHelper data4 = new PieHelper(35, “data4”);
        dataList.add(data4);
        // anchor dataList to pie_view
        pie_view.setDate(dataList);
        pie_view.showPercentLabel(true);
    }
}

Well, these all the java class that we have to create in our src folder.
src folder

Now Run the Project.