Android animation character in SurfaceView

I want to animate a character (like running a dog) on ​​the screen. AnimationDrawable looked perfect for this, and AnimationDrawable requires an ImageView. How to add and move ImageView in SurfaceView?

Thanks.

+2
source share
2 answers

You do not need ImageView .

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

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

Then set its borders and draw on the canvas:

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

You also need to manually configure the animation to start the next scheduled interval. You can do this by creating a new callback using animation.setCallback , then instantiating android.os.Handler and using the handler.postAtTime method to add the next animation frame to the current Thread 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(); 
+3
source

With SurfaceView, you are responsible for ensuring that everything is in it. You do not need AnimationDrawable or any representation to display your character on it. Check out the Google Lunar Lander game .

0
source

All Articles