Draw Pie Chart in Android?

前端 未结 5 1400
耶瑟儿~
耶瑟儿~ 2020-12-14 12:09

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

5条回答
  •  無奈伤痛
    2020-12-14 12:51

    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;
        }
    }
    

提交回复
热议问题