在SurfaceView机器人动画人物 [英] Android animate character in SurfaceView
问题描述
我要一个字符(如运行狗)屏幕上的动画。 AnimationDrawable似乎非常适合这一点,AnimationDrawable需要一个ImageView的。如何添加和左右移动的ImageView在SurfaceView?
I want to animate a character (for eg run a dog) on screen. AnimationDrawable seemed a perfect fit for this, and AnimationDrawable requires an ImageView. How do I add and move around the ImageView in SurfaceView?
感谢。
推荐答案
您不需要的ImageView
。
如果你的动画是 XML可绘制
,您可以从资源直接加载
到 AnimationDrawable
变量:
If your animation is an XML Drawable
, you can load it directly from the Resources
into an AnimationDrawable
variable:
Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);
然后设置它的边界,并绘制在画布上:
Then set it's bounds and draw on the canvas:
animation.setBounds(left, top, right, bottom);
animation.draw(canvas);
您还需要手动设置动画上运行它的下一个预定的时间间隔。这可以通过使用创建一个新的回调 animation.setCallback
,然后实例化一个 android.os.Handler
和使用来实现在 handler.postAtTime
方法,将一个动画帧添加到当前发
的消息队列。
You also need to manually set the animation to run on it's next scheduled interval. This can be accomplished by creating a new Callback using animation.setCallback
, then instantiating an android.os.Handler
and using the handler.postAtTime
method to add the next animation frame to the current Thread
's message queue.
animation.setCallback(new Callback() {
@Override
public void unscheduleDrawable(Drawable who, Runnable what) {
return;
}
@Override
public void scheduleDrawable(Drawable who, Runnable what, long when) {
//Schedules a message to be posted to the thread that contains the animation
//at the next interval.
//Required for the animation to run.
Handler h = new Handler();
h.postAtTime(what, when);
}
@Override
public void invalidateDrawable(Drawable who) {
return;
}
});
animation.start();
这篇关于在SurfaceView机器人动画人物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!