我想在屏幕上为角色设置动画(例如跑狗)。 AnimationDrawable 似乎非常适合这个,而 AnimationDrawable 需要一个 ImageView。如何在 SurfaceView 中添加和移动 ImageView?
谢谢。
最佳答案
您不需要 ImageView
。
如果您的动画是 XML Drawable
,您可以将它直接从 Resources
加载到 AnimationDrawable
变量中:
Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);
然后设置它的边界并在 Canvas 上绘制:
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 中的 Android 动画角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6531246/