Search This Blog

Sunday, March 31, 2013

Draw PieChart in android using View

Fitst of all make an Relative layout as the below in your XML file to Display Pie chart on that view.


       android:orientation="horizontal" >

Now we have to make a View which make the actual pie chart and draw and fill the color in the chart. Create one file let's say extends View and add the following code snippet in it.

public class DrawPieChart extends View {

Paint paint = new Paint();
        //  Here you can Add number of different color according to max different colors to be displayed on Piechart
        int c[] = {Color.MAGENTA,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW,Color.GREEN};
Canvas mCanvas = new Canvas();
private int[] values;
Context context;

public DrawPieChart(Context context, int[] values) {
paint = new Paint();
this.values = values;
// this.labels = labels;

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float t = getTotal();
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = values.length;
float cuurPos = -90;
RectF rect = new RectF(20,20,x-20,y-20);
for (int i = 0; i < n; i++) {
float thita =(t==0)?0: 360*values[i]/t;
canvas.drawArc(rect, cuurPos, thita, true, paint);
cuurPos = cuurPos+thita;

private float getTotal() {
int total = 0;
for (int i = 0; i < values.length; i++) {
total = total + values[i];
return total;

Now create an object of this class in your activity and pass the Array of the values to the object and it will create the Piechart in the Relative layout. You have to add this view in the Activity to your relative layout.

class Piechart extends Activity{

        RelativeLayout la;
DrawPieChart piView;
        int[] vals;

public void onCreate(Bundle savedInstanceState) {
                la = (RelativeLayout) findViewById(;
        public void  getPieChart(){
             vals[] = new vals[YOUR SIZE OF ARRAY];
             vals = {12,14,23,35,23,56,78};
             piView = new DrawPieChart(Analisys.this, vals);

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.