Android animate character in SurfaceView
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 move around the ImageView in SurfaceView?
Thanks开发者_如何学Python.
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();
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.
精彩评论