How to create circular progress bar(pie chart) like indicator - Android

前端 未结 5 2014
北恋
北恋 2020-12-08 08:05

Now I have a horizontal progress bar which is updated programmatically via ProgressBar setProgress method:



        
5条回答
  •  半阙折子戏
    2020-12-08 09:08

    You can either make a custom view (e.g. PieProgressView) or a custom Drawable (e.g. PieProgressDrawable). I took the custom view approach but either is perfectly viable.

    A quick look at the source for Android's ProgressView yields a wildly complex implementation. Obviously, they are covering all their bases, but you don't have to write something that complex. We really only need two things:

    1. A member to keep track of the current progress.
    2. A method to draw the pie based on the current progress.

    Number one is easy, just keep a member field that tracks the current percentage of the pie to draw. Number 2 is a bit more complicated but, luckily, we can do it with the standard Canvas draw methods.

    Conveniently, Android's Canvas class provides a drawArc() method. You can use this to get your Pie effect. Assuming we stored our percentage in a member field called mPercent as a float between 0 and 1, an onDraw() method might look like this:

    @Override
    protected void onDraw(Canvas canvas) {
    
        final float startAngle = 0f;
        final float drawTo = startAngle + (mPercent * 360);
    
        // Rotate the canvas around the center of the pie by 90 degrees
        // counter clockwise so the pie stars at 12 o'clock.
        canvas.rotate(-90f, mArea.centerX(), mArea.centerY());
        canvas.drawArc(mArea, startAngle, drawTo, true, mPaint);
    
        // Draw inner oval and text on top of the pie (or add any other
        // decorations such as a stroke) here..
        // Don't forget to rotate the canvas back if you plan to add text!
        ...
    }
    

    Here's what the completed view looks like in a sample app:

    PieProgressView in action!

    Edit

    Since posting, I've decided there's really no reason you need to implement a custom view. You can simply use a drawable and it's level property to do exactly what is needed. I made a gist with the full drawable.

提交回复
热议问题