在SurfaceView中实现Android角色动画

3
我希望在屏幕上制作一个动画角色(比如奔跑的狗)。AnimationDrawable似乎非常适合这个需求,而AnimationDrawable需要一个ImageView。我该如何在SurfaceView中添加和移动ImageView呢?
谢谢。
2个回答

5

您不需要一个 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();

1
你为什么不重用 Handler? - RichieHH

0

使用SurfaceView时,您需要负责在其中绘制所有内容。您不需要AnimationDrawable或任何视图来渲染其中的角色。可以参考Google的月球着陆者示例游戏。


谢谢Burov,所以AnimationDrawable不适合游戏吗? - droidbee
是的。AnimationDrawable不是一个视图,正如nmelo所解释的那样,您可以使用它。 - RichieHH

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接