I have been doing a lot of research, but I cannot find a clear example on rendering a spritesheet as an animation. I have this sprite sheet:
I will appreciate a lot of sample code on loading this efficiently
The way of doing this is pretty simple,
What you'll need before you start to code to separate your sprite into different separate image files, each files represents a frame in your animation. Note: You can achieve the above via code, but that's another issue.
1. Now you will need to create an xml file that will be your animation. The xml will be in res/drawble.
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">
<item android:drawable="@drawable/exp0" android:duration="100"/>
<item android:drawable="@drawable/exp1" android:duration="100"/>
<item android:drawable="@drawable/exp2" android:duration="100"/>
.
.
Where each item, is a frame (by order) - exp0 is the first frame exp1 is he second and so on.
android:oneshot="true"
Will make your animation go through the loop once and then keep the last frame displayed. The rest of the code is pretty self-explanatory (duration is in millis).
2. You will need to assign the xml file to a View and start it.
Lets say we want this animation to be displayed on a "tileView" object in a grid (You can do so to any View)
tileView.setImageResource(R.drawable.explosion_animation);
AnimationDrawable explosionAnimation = (AnimationDrawable)tileView.getDrawable();
explosionAnimation.start();
What we do here is set the xml that is our animation as the ImageResource (explosion_animation is the xml file we created) Then we get the animation itself into an AnimationDrawable object. Finally we start the animation.
You can store the sprites as an array of Rect
s.
Rect[] frames = new Rect[TOTAL_NUMBER_OF_FRAMES];
Your sheet appears to have equally spaced sprites, so you could have a nested for loop that fills the array mathematically. (Note you may want to set BitMapFactory Options to not scale your bitmap).
You can draw the nth frame with:
canvas.drawBitmap(bmp, frames[n],
new RectF(x, y, x + frames[n].width(), y + frames[n].height()),
paint);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With