我想在屏幕上为角色设置动画(例如运行狗)。 AnimationDrawable似乎非常适合这一点,而AnimationDrawable需要一个ImageView。如何在SurfaceView中添加和移动ImageView?SurfaceView中的Android动画角色
谢谢。
我想在屏幕上为角色设置动画(例如运行狗)。 AnimationDrawable似乎非常适合这一点,而AnimationDrawable需要一个ImageView。如何在SurfaceView中添加和移动ImageView?SurfaceView中的Android动画角色
谢谢。
使用SurfaceView,您有责任绘制其中的所有内容。你不需要AnimationDrawable或任何视图来渲染你的角色。看看谷歌的示例游戏Lunar Lander。
你不需要ImageView
。
如果你的动画是一个XML Drawable
,您可以直接从Resources
加载到一个AnimationDrawable
变量:
Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);
然后将其设置的界限,并在画布上绘制:也
animation.setBounds(left, top, right, bottom);
animation.draw(canvas);
你需要手动将动画设置为在下一个计划时间间隔运行。这可以通过使用animation.setCallback
创建新的回调,然后实例化android.os.Handler
并使用handler.postAtTime
方法将下一个动画帧添加到当前的Thread
的消息队列来实现。
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();
有没有理由不重用Handler? – RichieHH
感谢Burov,所以AnimationDrawable不适合游戏吗? – droidbee
是的。 AnimationDrawable不是视图,您可以按照nmelo的说明使用它。 – RichieHH