如何创建类似指示器的圆形进度条(饼图) - Android [英] How to create circular progress bar(pie chart) like indicator - Android
问题描述
现在我有一个水平进度条,它通过 ProgressBar
setProgress
方法以编程方式更新:
有没有办法将此进度条转换为圆形(饼图)并能够以编程方式更新进度?
我想要的例子:
您可以创建自定义视图(例如 PieProgressView)或自定义 Drawable(例如 PieProgressDrawable).我采用了自定义视图方法,但两者都非常可行.
快速浏览 Android .
Now I have a horizontal progress bar which is updated programmatically via ProgressBar
setProgress
method:
<ProgressBar
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="20dip"
android:id="@+id/progressbar"
>
</ProgressBar>
Is there a way to convert this progress bar to a circle (pie chart) and to be able also to update the progress programmatically?
Example of what I want:
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:
- A member to keep track of the current progress.
- 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:
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.
这篇关于如何创建类似指示器的圆形进度条(饼图) - Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!