65.9K
CodeProject is changing. Read more.
Home

Simple Pie Chart with Labels

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.91/5 (4 votes)

Sep 14, 2014

CPOL
viewsIcon

32153

downloadIcon

2278

Logic to create Pie chart with rotated labels

Introduction

This library contains simple ways to create a pie chart with basic interaction and labels.

Steps to Implement

  1. Calculate the percentage of the values.
  2. We can find sweep angle with percentage.
  3. Add the current pie slice sweep angle with previous pie slice end angle.
  4. Create new pie slice view with start angle and sweep angle (Make sure to apply a different color for each pie splice).

Code

Iterate all the points and calculate the angle and add pie slice to the layout.

total = 0;
for (int i = 0; i < data.length; i++) {
    total += data[i];
}
float startAngle = 0, sweepAngle;
for (int i = 0; i < data.length; i++) {
    sweepAngle = data[i] * (360f / total);
    PieSlice pieSlice = new PieSlice(getContext(), this);
    pieSlice.startAngele = startAngle;
    pieSlice.sweepAngle = sweepAngle;
    addView(pieSlice);
    pieSlices.add(pieSlice);
    pieSlice.paint.setColor(palette[i % 6]);
    startAngle += sweepAngle;
}

Draw pie slice with the above created points.

canvas.drawArc(oval, startAngele, sweepAngle, true, paint);

float angle = (startAngele + (sweepAngle / 2)) * D_TO_R;

canvas.save();

if (label != null) {
    labelPaint.getTextBounds(label, 0, label.length(), labelRect);
    float x = oval.centerX() + (float) Math.cos(angle) * (oval.width() / 4 + labelRect.width() / 2);
    float y = oval.centerY() + (float) Math.sin(angle) * (oval.height() / 4 + labelRect.width() / 2);
    x -= labelRect.width() / 2;
    canvas.rotate(startAngele + (sweepAngle / 2), x + labelRect.exactCenterX(), y + labelRect.exactCenterY());
    canvas.drawText(label, x, y, labelPaint);
}

canvas.restore();

Output

Steps to Run Sample

Android Studio

  1. Unzip the PieChart.zip folder.
  2. Create new project in Android studio.
  3. File --> Import module, import Library and sample module from extracted folder.
  4. Add the Library module dependency to Sample module.

Eclipse

Indirect solution:

  1. Create new project with two modules.
  2. Replace all the required files from extracted PieChart folder.