上一节我们讲了补间动画,接下来我们来学习逐帧动画。
Android中的逐帧动画是将一系列静止的画面按一定的顺序和速度进行播放从而产生的动画效果,当然静止的画面指的就是帧了,反映在我们的代码中就是一张张图片。ps:这里插一个小概念,我们玩游戏或者看电影时经常会讲到的一个词,帧数,其实指的就是1秒内播放的帧数量,用fps来表示画面传输率,一般电影播放为24帧,也就是一秒播放24个画面,游戏有30帧到60帧或者更高,更高的帧数表现为画面更加流畅,没有卡顿感。
多说无益,代码才是王道,下面我们就来实现Android中的逐帧动画,依然是分为两种方式:
xml
FrameAnimation的定义与TweenAnimation不同,它是定义在res/drawable目录下,用法如下:
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item android:drawable="@mipmap/anim_frame_1" android:duration="42"/>
<item android:drawable="@mipmap/anim_frame_2" android:duration="42"/>
...
<item android:drawable="@mipmap/anim_frame_27" android:duration="42"/>
<item android:drawable="@mipmap/anim_frame_28" android:duration="42"/>
</animation-list>
可以看到,其实就是画面的堆叠,oneshot属性是指动画是否仅执行一次,设置为false则说明重复执行,设置为true则代表执行一次后停止。item属性很简单,只有两个,drawable设置该帧,duration设置该帧显示时长。那么这个xml的用法也很简单,可以将这个动画文件当做一个drawable来使用,设置给某个view作为背景,如下:
<View
android:id="@+id/view_anim_container"
android:layout_margin="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/anim_list_match_man"/>
然后在Java代码中调用:
private void init() {
animContainer = findViewById(R.id.view_anim_container);
animationDrawable = (AnimationDrawable) animContainer.getBackground();
}
/**
* 开启动画
*/
protected void startAnim(View view) {
animationDrawable.start();
}
/**
* 停止动画
*/
protected void stopAnim(View view) {
animationDrawable.stop();
}
使用很简单,取出Drawable,强转为AnimationDrawable(逐帧动画的帮助类),该类常用的方法就是start()开启动画和stop()停止动画。使用方法很简单,不细说,接下来是纯java代码的实现:
Java
纯java生成的方式也非常简单,直接撸代码:
animationDrawable = new AnimationDrawable();
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.anim_frame_28),42);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.anim_frame_27),42);
...
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.anim_frame_2),42);
animationDrawable.addFrame(getResources().getDrawable(R.mipmap.anim_frame_1),42);
animContainer.setBackgroundDrawable(animationDrawable);//将动画设置给view
开启方法与上面的xml实现一样,不在多说
实现效果就是下图这样子了,一个火柴人互殴的动画,原图太长了放不下,只截取了一点点:
可以看到java实现是把动画帧倒序排列实现了倒播的效果。
ok,到这里我们的FrameAnimation就了解完了,比起Tween动画可简单太多了不是吗。代码地址在github,欢迎下载查看、拍砖~
See you~