Android animate character in SurfaceView

后端 未结 2 737
失恋的感觉
失恋的感觉 2021-01-14 17:34

I want to animate a character (for eg run a dog) on screen. AnimationDrawable seemed a perfect fit for this, and AnimationDrawable requires an ImageView. How do I add and mo

相关标签:
2条回答
  • 2021-01-14 17:36

    You don't need an ImageView.

    If your animation is an XML Drawable, you can load it directly from the Resources into an AnimationDrawable variable:

    Resources res = context.getResources();
    AnimationDrawable animation = (AnimationDrawable)res.getDrawable(R.drawable.anim);      
    

    Then set it's bounds and draw on the canvas:

    animation.setBounds(left, top, right, bottom);
    animation.draw(canvas);
    

    You also need to manually set the animation to run on it's next scheduled interval. This can be accomplished by creating a new Callback using animation.setCallback, then instantiating an android.os.Handler and using the handler.postAtTime method to add the next animation frame to the current Thread's message queue.

    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();
    
    0 讨论(0)
  • 2021-01-14 17:57

    With a SurfaceView it is your responsibility to draw everything within it. You do not need AnimationDrawable or any view to render your character on it. Take a look onto Lunar Lander example game from Google.

    0 讨论(0)
提交回复
热议问题