自定义Android PieChart

时间:2014-04-04 09:49:39

标签: android view android-activity geometry pie-chart

我正在尝试以下列方式设计饼图:

Pie Chart with sectors

但到目前为止,我已经能够做到这一点:

Result Image

为了在android中设计饼图,我使用了自定义视图类。作为参考,您可以在下面找到它:

public class PieChartView extends View {

private int[] values = {30, 60, 90, 100, 150};
private int c[] = {Color.MAGENTA,Color.BLUE,Color.RED,Color.CYAN,Color.YELLOW};
private int valuesLength = values.length;
private RectF rectF;
private Paint slicePaint;

public PieChartView(Context context, AttributeSet attrs) {
    super(context, attrs);

    valuesLength = values.length;
    slicePaint = new Paint();
    slicePaint.setAntiAlias(true);
    slicePaint.setDither(true);
    slicePaint.setStyle(Paint.Style.FILL);
}

@Override
protected void onDraw(Canvas canvas) {
    MainActivity.getLog("=====On draw called=====");

    if(values != null) {
        int startTop = 0;
        int startLeft = 0;
        int endBottom = getHeight();
        int endRight = endBottom;// This makes an equal square.

        rectF = new RectF(startLeft, startTop, endRight, endBottom);

        float[] scaledValues = scale();
        float sliceStartPoint = 0;
        for(int i = 0; i < valuesLength; i++) {
            slicePaint.setColor(c[i]);
            MainActivity.getLog("Slice starting point:::::"+sliceStartPoint);
            MainActivity.getLog("Scaled Value:::::"+scaledValues[i]);
            canvas.drawArc(rectF, sliceStartPoint, scaledValues[i], true, slicePaint);//This draws each slice

            MainActivity.getLog("Rectangle height:::::"+rectF.height());
            sliceStartPoint += scaledValues[i];//This updates the starting point of next slice.
        }
        //Inner Paint object
        Paint innerPaintObj = new Paint();
        innerPaintObj.setColor(Color.GREEN);
        innerPaintObj.setStyle(Paint.Style.FILL);
        innerPaintObj.setAntiAlias(true);
        canvas.drawCircle(getWidth()/2, getHeight()/2, 100, innerPaintObj);
    }
}

/*The scaling method scales calculations will be as follows:

    For index 0: (300 / 2275) * 360 = 47.47252747252747  (This will occupy 48 out of 360)
    For index 1: (1500 / 2275) * 360 = 237.3626373626374 (This will occupy 237 out of 360)
    For index 2: (475 / 2275) * 360 = 75.16483516483516 (This will occupy 75 out of 360)
*/

private float[] scale() {
    float[] scaledValues = new float[this.values.length];
    float total = getTotal(); //Total all values supplied to the chart
    for (int i = 0; i < this.values.length; i++) {
        scaledValues[i] = (this.values[i] / total) * 360; //Scale each value
    }
    return scaledValues;
}

 private float getTotal() {
        float total = 0;
        for (float val : this.values)
            total += val;
        return total;
    }
}

如果有人可以告诉我内圆应该如何透明,以及如何从中途填充这些扇区,那将会很有帮助。

感谢。

0 个答案:

没有答案