Skip to content Skip to sidebar Skip to footer

Android Donut Chart

I have created a donut chart, which is shown below: MY resultant Donut chart should be in the following way: My Question is, How can i achieve the lines with image (They are roun

Solution 1:

Here's how i finally did it after two days of search with help of this library https://github.com/Ken-Yang/AndroidPieChart

And equations to center text done with help of my friends and alot of search

on MainActivity onCreate or oncreateView if you are using fragments:

PieChart pie = (PieChart) rootView.findViewById(R.id.pieChart);

    ArrayList<Float> alPercentage = new ArrayList<Float>();
    alPercentage.add(2.0f);
    alPercentage.add(8.0f);
    alPercentage.add(20.0f);
    alPercentage.add(10.0f);
    alPercentage.add(10.0f);
    alPercentage.add(10.0f);
    alPercentage.add(10.0f);
    alPercentage.add(10.0f);
    alPercentage.add(10.85f);
    alPercentage.add(9.15f);
    try {
        // setting data
        pie.setAdapter(alPercentage);

        // setting a listener
        pie.setOnSelectedListener(new OnSelectedLisenter() {
            @Override
            publicvoidonSelected(int iSelectedIndex) {
                Toast.makeText(getActivity(),
                        "Select index:" + iSelectedIndex,
                        Toast.LENGTH_SHORT).show();
            }
        });
    } catch (Exception e) {
        if (e.getMessage().equals(PieChart.ERROR_NOT_EQUAL_TO_100)) {
            Log.e("kenyang", "percentage is not equal to 100");
        }
    }



publicclassPieChartextendsView {

publicinterfaceOnSelectedLisenter {
    publicabstractvoidonSelected(int iSelectedIndex);
}

private OnSelectedLisenter onSelectedListener = null;

privatestatic final String TAG = PieChart.class.getName();
publicstatic final String ERROR_NOT_EQUAL_TO_100 = "NOT_EQUAL_TO_100";
privatestatic final int DEGREE_360 = 360;
privatestatic String[] PIE_COLORS = null;
privatestaticint iColorListSize = 0;
ArrayList<Float> array;
private Paint paintPieFill;
private Paint paintPieBorder;
private Paint paintCenterCircle;
private ArrayList<Float> alPercentage = new ArrayList<Float>();
privateint mCenterX = 320;
privateint mCenterY = 320;
privateint iDisplayWidth, iDisplayHeight;
privateint iSelectedIndex = -1;
privateint iCenterWidth = 0;
privateint iShift = 0;
privateint iMargin = 0; // margin to left and right, used for get Radiusprivateint iDataSize = 0;
private Canvas canvas1;
private RectF r = null;
private RectF centerCircle = null;
privatefloat fDensity = 0.0f;
privatefloat fStartAngle = 0.0f;
privatefloat fEndAngle = 0.0f;
float fX;
float fY;

publicPieChart(Context context, AttributeSet attrs) {
    super(context, attrs);
    PIE_COLORS = getResources().getStringArray(R.array.colors);
    iColorListSize = PIE_COLORS.length;
    array = new ArrayList<Float>();
    fnGetDisplayMetrics(context);
    iShift = (int) fnGetRealPxFromDp(30);
    iMargin = (int) fnGetRealPxFromDp(40);
    centerCircle = new RectF(200, 200, 440, 440);
    // used for paint circle
    paintPieFill = new Paint(Paint.ANTI_ALIAS_FLAG);
    paintPieFill.setStyle(Paint.Style.FILL);
    // used for paint centerCircle
    paintCenterCircle = new Paint(Paint.ANTI_ALIAS_FLAG);
    paintCenterCircle.setStyle(Paint.Style.FILL);
    paintCenterCircle.setColor(Color.WHITE);
    // used for paint border
    paintPieBorder = new Paint(Paint.ANTI_ALIAS_FLAG);
    paintPieBorder.setStyle(Paint.Style.STROKE);
    paintPieBorder.setStrokeWidth(fnGetRealPxFromDp(3));
    paintPieBorder.setColor(Color.WHITE);
    Log.i(TAG, "PieChart init");

}

// set listenerpublicvoidsetOnSelectedListener(OnSelectedLisenter listener) {
    this.onSelectedListener = listener;
}

float temp = 0;

@Override
protectedvoidonDraw(Canvas canvas) {
    super.onDraw(canvas);
    Log.i(TAG, "onDraw");
    float centerX = (r.left + r.right) / 2;
    float centerY = (r.top + r.bottom) / 2;
    float radius1 = (r.right - r.left) / 2;
    radius1 *= 0.5;
    float startX = mCenterX;
    float startY = mCenterY;
    float radius = mCenterX;
    float medianAngle = 0;
    Path path = new Path();

    for (int i = 0; i < iDataSize; i++) {

        // check whether the data size larger than color list sizeif (i >= iColorListSize) {
            paintPieFill.setColor(Color.parseColor(PIE_COLORS[i
                    % iColorListSize]));
        } else {
            paintPieFill.setColor(Color.parseColor(PIE_COLORS[i]));
        }

        fEndAngle = alPercentage.get(i);

        // convert percentage to angle
        fEndAngle = fEndAngle / 100 * DEGREE_360;

        // if the part of pie was selected then change the coordinateif (iSelectedIndex == i) {
            canvas.save(Canvas.MATRIX_SAVE_FLAG);
            float fAngle = fStartAngle + fEndAngle / 2;
            double dxRadius = Math.toRadians((fAngle + DEGREE_360)
                    % DEGREE_360);
            fY = (float) Math.sin(dxRadius);
            fX = (float) Math.cos(dxRadius);
            canvas.translate(fX * iShift, fY * iShift);
        }

        canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieFill);
        float angle = (float) ((fStartAngle + fEndAngle / 2) * Math.PI / 180);
        float stopX = (float) (startX + (radius/2) * Math.cos(angle));
        float stopY = (float) (startY + (radius/2) * Math.sin(angle));


        // if the part of pie was selected then draw a borderif (iSelectedIndex == i) {
            canvas.drawArc(r, fStartAngle, fEndAngle, true, paintPieBorder);
             canvas.drawLine(startX, startY, stopX, stopY, paintPieFill);
            canvas.restore();
        }
        fStartAngle = fStartAngle + fEndAngle;
    }

}

@Override
protectedvoidonMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    // get screen size
    iDisplayWidth = MeasureSpec.getSize(widthMeasureSpec);
    iDisplayHeight = MeasureSpec.getSize(heightMeasureSpec);

    if (iDisplayWidth > iDisplayHeight) {
        iDisplayWidth = iDisplayHeight;
    }

    /*
     * determine the rectangle size
     */
    iCenterWidth = iDisplayWidth / 2;
    int iR = iCenterWidth - iMargin;
    if (r == null) {
        r = new RectF(iCenterWidth - iR, // top
                iCenterWidth - iR, // left
                iCenterWidth + iR, // right
                iCenterWidth + iR); // bottom
    }
    if (centerCircle == null) {
        // centerCircle=new RectF(left, top, right, bottom);

    }
    setMeasuredDimension(iDisplayWidth, iDisplayWidth);
}

@Override
public boolean onTouchEvent(MotionEvent event) {

    // get degree of the touch pointdouble dx = Math.atan2(event.getY() - iCenterWidth, event.getX()
            - iCenterWidth);
    float fDegree = (float) (dx / (2 * Math.PI) * DEGREE_360);
    fDegree = (fDegree + DEGREE_360) % DEGREE_360;

    // get the percent of the selected degreefloat fSelectedPercent = fDegree * 100 / DEGREE_360;

    // check which pie was selectedfloat fTotalPercent = 0;
    for (int i = 0; i < iDataSize; i++) {
        fTotalPercent += alPercentage.get(i);
        if (fTotalPercent > fSelectedPercent) {
            iSelectedIndex = i;
            break;
        }
    }
    if (onSelectedListener != null) {
        onSelectedListener.onSelected(iSelectedIndex);
    }
    invalidate();
    return super.onTouchEvent(event);
}

privatevoidfnGetDisplayMetrics(Context cxt) {
    final DisplayMetrics dm = cxt.getResources().getDisplayMetrics();
    fDensity = dm.density;
}

privatefloatfnGetRealPxFromDp(float fDp) {
    return (fDensity != 1.0f) ? fDensity * fDp : fDp;
}

publicvoidsetAdapter(ArrayList<Float> alPercentage) throws Exception {
    this.alPercentage = alPercentage;
    iDataSize = alPercentage.size();
    float fSum = 0;
    for (int i = 0; i < iDataSize; i++) {
        fSum += alPercentage.get(i);
    }
    if (fSum != 100) {
        Log.e(TAG, ERROR_NOT_EQUAL_TO_100);
        iDataSize = 0;
        thrownew Exception(ERROR_NOT_EQUAL_TO_100);
    }

}


<com.example.piecharts.PieChart
        android:id="@+id/pieChart"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </com.example.piecharts.PieChart>

Post a Comment for "Android Donut Chart"