如何在Android中为弧形图制作动画 [英] How to animate the drawing of arc in android
问题描述
我是Android的新手,我正在使用drawArc函数向用户显示某些任务的进度,但是现在我希望对此进行动画处理,使其看起来好像正在增长。
I am new to Android and I am using the drawArc function to show the progress of some task to the user but now I want to animate this so that it looks as if it is growing.
我使用以下代码但不起作用:
I use the following code but not working:
new Thread(new Runnable() {
int i=0;
float startAngle =0;
float swipeAngle = 40.7f;
public void run() {
while (i < swipeAngle) {
canvas.drawArc(rectF, startAngle, i, false, paint);
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
i++;
}
}).start();
有人可以建议这有什么问题吗,或者可以建议其他想法进行动画处理。
Can Someone Please suggest whats wrong in this or Can suggest some other idea to animate.
推荐答案
Android编程的最重要规则之一是,您应该限制在 onDraw $中所做的事情c $ c>越多越好。理想情况下,您不应在
onDraw
方法中分配任何内容。只需在画布
上绘制。
One of the most important rules of programming for Android is that you should limit things you do in onDraw
as much as you can. Ideally you shouldn't be allocating anything in onDraw
method. Just drawing on canvas
.
不幸的是,这只是代码的第一件事。
And unfortunately that's only the first thing that is wrong with your code.
您应该这样考虑:单个 canvas
对象仅在单个(简单) onDraw
方法调用。因此,您不能在单独的线程中重用它。
You should think about it this way: a single canvas
object is only viable during a single (simple) onDraw
method call. So you cannot reuse it inside a separate thread.
对于您的情况,您应该启动一个单独的线程(就像您在示例中所做的一样),但是在其中,您应该只更新 View的
字段,它表示圆弧的角度并要求您重新绘制 View
( invalidate()
For your case you should start a separate thread (just like you did in your example), but inside it you should only update a View's
field that represents the arc's angle and ask for your View
to redraw (the invalidate()
method).
public class TestView extends View {
private float currentAngle;
//... some needed methods (be sure to init rectF and paint somewhere here)
public void startAnimatingArc(final float maxAngle) {
currentAngle = 0;
new Thread(new Runnable() {
public void run() {
while (currentAngle < maxAngle) {
invalidate();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
currentAngle++;
}
}).start();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawArc(rectF, 0, currentAngle, false, paint);
// you should try not to add anything else in this call
// (unless you want to draw something else as well)
}
}
整个动画代码架构也可能会更好。但是主要的问题是与 canvas
交互有关,所以这就是我在您的代码中更正的内容。
The whole "animation" code architecture could be much better as well. But the main problem is with the canvas
interaction, so that's what I corrected in your code.
这篇关于如何在Android中为弧形图制作动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!