Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Doughnut Chart Similar to Google Fit

Does anyone know how to create a doughnut chart similar to the one in Google Fit.

Google Fit Chart

like image 370
Chris D Avatar asked Mar 26 '15 14:03

Chris D


2 Answers

I also wanted this, but the best answer i could find was "make your own". So I did.

This is pretty basic (I'm new to android) and unfinished, but it should give you the idea.

Basically, you just set up your paint objects

    paintPrimary = new Paint();
    paintPrimary.setAntiAlias(true);
    paintPrimary.setColor(colorPrimary);
    paintPrimary.setStyle(Paint.Style.STROKE);
    paintPrimary.setStrokeCap(Paint.Cap.ROUND);

and call canvas.drawArc

class FitDoughnutView extends View {

    private RectF _oval;

    public FitDoughnutView(Context ctx) {
        super(ctx);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        canvas.drawArc(_oval, 0, 360, false, paintSecondary);

        canvas.drawArc(_oval, 270, percentDeg, false, paintPrimary);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        _oval = new RectF(width, width, w - width, h - width);
    }
}

Full source here: github.com/tehmantra/fitdoughnut

Someone's tutorial: hmkcode.com/android-canvas-how-to-draw-2d-donut-chart/

like image 89
Michael Wildman Avatar answered Nov 08 '22 04:11

Michael Wildman


I would recommend this library because it's actively maintained and has a lot of options.

It has a guide of how to use it in Kotlin, but you also can use it in Java like this:

In your layout file:

<app.futured.donut.DonutProgressView
        android:id="@+id/dpvChart"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_marginTop="8dp"
        app:donut_bgLineColor="@color/grey"
        app:donut_gapAngle="270"
        app:donut_gapWidth="20"
        app:donut_strokeWidth="16dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

Then in your Java Activity:

private DonutProgressView dpvChart;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    dpvChart = findViewById(R.id.dpvChart);

    DonutSection section = new DonutSection("Section 1 Name", Color.parseColor("#f44336"), 80.0f);
    dpvChart.setCap(100f);
    dpvChart.submitData(new ArrayList<>(Collections.singleton(section)));
}
like image 24
Brugui Avatar answered Nov 08 '22 02:11

Brugui