如何打造循环进度条(饼图),如指示灯 - 机器人指示灯、机器人、如何打造、进度条

2023-09-03 23:21:16 作者:是wǒ把太阳磨圆滴

现在我有一个水平进度条是通过进度 setProgress 编程更新方法:

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?

是我想举例:

推荐答案

您可以创建自定义视图(如 PieProgressView 的)或自定义绘制对象(比如 PieProgressDrawable 的) 。我把自定义视图的方法,但是要么是完全可行的。

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.

有一个快速浏览一下源代码Android的ProgressView产生了广泛复杂的实现。显然,他们都涵盖了所有的基地,但你不必写的东西复杂。我们真的只需要两样东西:

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:

的成员来跟踪目前的进展情况。 系统来绘制根据目前的进度饼的方法。

第一是容易的,只要保持跟踪馅饼吸取的电流百分比的成员字段。 2号是一个比较复杂一点,但是,幸运的是,我们可以使用标准的画布绘制方法做到这一点。

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.

方便的是,Android的帆布类提供了一个drawArc()方法。你可以用它来让你的派的效果。假设我们保存在我们的百分比称为一个成员字段的 mPercent 的为0和1之间的浮点,一个的OnDraw()的方法可能是这样的:

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:

修改

自从发布,我决定真的没有原因,你需要实现一个自定义视图。你可以简单地用一个绘制,它的级别属性做需要的到底是什么。我做了一个要点与完整绘制。

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.