我希望在屏幕上制作一个动画角色(比如奔跑的狗)。AnimationDrawable似乎非常适合这个需求,而AnimationDrawable需要一个ImageView。我该如何在SurfaceView中添加和移动ImageView呢?
谢谢。
谢谢。
您不需要一个 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();
使用SurfaceView时,您需要负责在其中绘制所有内容。您不需要AnimationDrawable或任何视图来渲染其中的角色。可以参考Google的月球着陆者示例游戏。