SurfaceView 中的 Android 动画角色

dro*_*bee 3 animation android surfaceview

我想在屏幕上制作一个角色的动画(例如遛狗)。AnimationDrawable 似乎非常适合这一点,并且 AnimationDrawable 需要 ImageView。如何在 SurfaceView 中添加和移动 ImageView?

谢谢。

nme*_*elo 5

你不需要一个ImageView.

如果您的动画是XML Drawable,您可以将其直接从 加载到变量ResourcesAnimationDrawable

Resources res = context.getResources();
AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);      
Run Code Online (Sandbox Code Playgroud)

然后设置它的边界并在画布上绘制:

animation.setBounds(left, top, right, bottom);
animation.draw(canvas);
Run Code Online (Sandbox Code Playgroud)

您还需要手动设置动画以在下一个计划间隔运行。这可以通过使用 创建一个新的回调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();
Run Code Online (Sandbox Code Playgroud)