1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
|
package de.danoeh.antennapod.view;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.Nullable;
import de.danoeh.antennapod.R;
import de.danoeh.antennapod.core.util.ThemeUtils;
public class CircularProgressBar extends View {
private static final float EPSILON = 0.005f;
private final Paint paintBackground = new Paint();
private final Paint paintProgress = new Paint();
private float percentage = 0;
private float targetPercentage = 0;
private Object tag = null;
private final RectF bounds = new RectF();
public CircularProgressBar(Context context) {
super(context);
setup();
}
public CircularProgressBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setup();
}
public CircularProgressBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setup();
}
private void setup() {
paintBackground.setAntiAlias(true);
paintBackground.setStyle(Paint.Style.STROKE);
paintProgress.setAntiAlias(true);
paintProgress.setStyle(Paint.Style.STROKE);
paintProgress.setStrokeCap(Paint.Cap.ROUND);
int color = ThemeUtils.getColorFromAttr(getContext(), R.attr.action_icon_color);
paintProgress.setColor(color);
paintBackground.setColor(color);
}
/**
* Sets the percentage to be displayed.
* @param percentage Number from 0 to 1
* @param tag When the tag is the same as last time calling setPercentage, the update is animated
*/
public void setPercentage(float percentage, Object tag) {
targetPercentage = percentage;
if (tag == null || !tag.equals(this.tag)) {
// Do not animate
this.percentage = percentage;
this.tag = tag;
}
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float padding = getHeight() * 0.07f;
paintBackground.setStrokeWidth(getHeight() * 0.02f);
paintProgress.setStrokeWidth(padding);
bounds.set(padding, padding, getWidth() - padding, getHeight() - padding);
canvas.drawArc(bounds, 0, 360, false, paintBackground);
if (percentage > EPSILON && 1 - percentage > EPSILON) {
canvas.drawArc(bounds, -90, percentage * 360, false, paintProgress);
}
if (Math.abs(percentage - targetPercentage) > EPSILON) {
float speed = 0.02f;
if (Math.abs(targetPercentage - percentage) < 0.1 && targetPercentage > percentage) {
speed = 0.006f;
}
float delta = Math.min(speed, Math.abs(targetPercentage - percentage));
float direction = ((targetPercentage - percentage) > 0 ? 1f : -1f);
percentage += delta * direction;
invalidate();
}
}
}
|