将一帧一帧的图片,按照一定的顺序和事件间隔播放。
借助 AnimationDrawable 实现播放。
添加图片有2中方式:
1、通过 drawable.xml 中添加帧图片,是否循环播放、帧动画播放时间;
2、通过 AnimationDrawable 中的 addFrame(@NonNull Drawable frame, int duration) 同样可以实现。
以第一种为例:
book_animation.xml 中 animation-list 标签代表图片集合
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="true">
<item android:drawable="@drawable/book1" android:duration="300"/>
<item android:drawable="@drawable/book2" android:duration="300"/>
<item android:drawable="@drawable/book3" android:duration="300"/>
<item android:drawable="@drawable/book4" android:duration="300"/>
</animation-list>
代码中获取集合,播放图片
ImageView bookAnim = findViewById(R.id.book_anim);
bookAnim.setBackgroundResource(R.drawable.book_animation);
AnimationDrawable frameAnimation = (AnimationDrawable) bookAnim.getBackground();
frameAnimation.start();
AnimationDrawable.java 代码梳理:
通过 inflate 解析xml,将解析结果 addFrame 添加入一个集合,start 移动帧
AnimationDrawable.java
private void setFrame(int frame, boolean unschedule, boolean animate) {
if (frame >= mAnimationState.getChildCount()) {
return;
}
mAnimating = animate;
mCurFrame = frame;
selectDrawable(frame);
if (unschedule || animate) {
unscheduleSelf(this);
}
if (animate) {
// Unscheduling may have clobbered these values; restore them
mCurFrame = frame;
mRunning = true;
scheduleSelf(this, SystemClock.uptimeMillis() + mAnimationState.mDurations[frame]);
}
}
Drawable.java 移动到下一帧
public void scheduleSelf(@NonNull Runnable what, long when) {
final Callback callback = getCallback();
if (callback != null) {
callback.scheduleDrawable(this, what, when);
}
}
AnimationDrawable.java
@Override
public void run() {
nextFrame(false);
}
private void nextFrame(boolean unschedule) {
int nextFrame = mCurFrame + 1;
final int numFrames = mAnimationState.getChildCount();
final boolean isLastFrame = mAnimationState.mOneShot && nextFrame >= (numFrames - 1);
// Loop if necessary. One-shot animations should never hit this case.
if (!mAnimationState.mOneShot && nextFrame >= numFrames) {
nextFrame = 0;
}
setFrame(nextFrame, unschedule, !isLastFrame);
}
通过代码添加代码如下:
// 通过代码加载
Resources resources = this.getResources();
Drawable book1 = resources.getDrawable(R.drawable.book1, null);
Drawable book2 = resources.getDrawable(R.drawable.book2, null);
Drawable book3 = resources.getDrawable(R.drawable.book3, null);
Drawable book4 = resources.getDrawable(R.drawable.book4, null);
AnimationDrawable animationDrawable = new AnimationDrawable();
animationDrawable.setOneShot(false);
animationDrawable.addFrame(book1, 300 );
animationDrawable.addFrame(book2, 300 );
animationDrawable.addFrame(book3, 300 );
animationDrawable.addFrame(book4, 300 );
bookAnim.setBackground(animationDrawable);
animationDrawable.start();