Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw Pie Chart in Android?

Tags:

android

I need to draw Pie Chart (Dynamic Values).How to create the Chart without using 3rd party API.

like image 506
Tester Avatar asked Dec 09 '10 10:12

Tester


People also ask

What app can I use to make pie chart?

SmartDraw makes it easy to add a pie chart to any diagram. Just import data and choose your graph time. You can also display the same data in different graph formats.


1 Answers

Basic function to draw a pie chart, input is an array of colors, and an array of values. They arrays must have the same size. The slices are callculated based on the values from each slide and the sum of all values.Ofcourse you can also change to float values. This solution is provided as an lightweight helper function. It's easy to use, and you do not need to define a class for it.

public static void drawPieChart(Bitmap bmp, int[] colors, int[] slices){
    //canvas to draw on it
    Canvas canvas = new Canvas(bmp);
    RectF box = new RectF(2, 2,bmp.getWidth()-2 , bmp.getHeight()-2);

    //get value for 100%
    int sum = 0;
    for (int slice : slices) {
        sum += slice;
    }
    //initalize painter
    Paint paint = new Paint();
    paint.setAntiAlias(true);

    paint.setStyle(Paint.Style.STROKE); 
    paint.setStrokeWidth(1f);
    paint.setStyle(Style.FILL_AND_STROKE);
    float start = 0;
    //draw slices
    for(int i =0; i < slices.length; i++){
        paint.setColor(colors[i]);
        float angle;
        angle = ((360.0f / sum) * slices[i]);
        canvas.drawArc(box, start, angle, true, paint);
        start += angle;
    }
}
like image 168
Waldschrat Avatar answered Oct 18 '22 02:10

Waldschrat