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.

<RelativeLayout

       android:id="@+id/piechart_lay"
       android:layout_width="150dip"
       android:layout_height="150dip"
       android:layout_margin="5dip"
       android:background="#eeffee"
       android:orientation="horizontal" >
</RelativeLayout>


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 DrawPieChart.java 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) {
super(context);
paint = new Paint();
this.values = values;
// this.labels = labels;
super.draw(mCanvas);
}

public void draw(Canvas canvas) {
int x = getWidth();
int y = getHeight();
float t = getTotal();
paint.setColor(Color.parseColor("#78777D"));
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
canvas.drawRect(0, 0, x - 1, y - 1, paint);
int n = values.length;
float cuurPos = -90;
paint.setStyle(Style.FILL);
RectF rect = new RectF(20,20,x-20,y-20);
for (int i = 0; i < n; i++) {
paint.setColor(c[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;


       @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.relative);
                la = (RelativeLayout) findViewById(R.id.pie_lay);
                getPieChart();
        }
        
        public void  getPieChart(){
             vals[] = new vals[YOUR SIZE OF ARRAY];
             vals = {12,14,23,35,23,56,78};
             piView = new DrawPieChart(Analisys.this, vals);
             
             la.removeAllViews();
     la.addView(piView); 
       }
}



No comments:

Post a Comment

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