上一篇介绍了Android的Tween Animation(补间动画) Android动画效果之Tween Animation(补间动画),今天来总结下Android的另一种动画Frame Animation(逐帧动画)。html
其余几种动画效果:java
逐帧动画(Frame-by-frame Animations)从字面上理解就是一帧挨着一帧的播放图片,就像放电影同样。和补间动画同样能够经过xml实现也能够经过java代码实现。接下来借助目前项目中的一个开奖的动画来总结如何使用。实现效果以下:android
<?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/lottery_1" android:duration="200" /> <item android:drawable="@mipmap/lottery_2" android:duration="200" /> <item android:drawable="@mipmap/lottery_3" android:duration="200" /> <item android:drawable="@mipmap/lottery_4" android:duration="200" /> <item android:drawable="@mipmap/lottery_5" android:duration="200" /> <item android:drawable="@mipmap/lottery_6" android:duration="200" /> </animation-list>
根节点是animation-list(动画列表),里面有一个或者多个item节点组成,oneshot属性表示是否只播放一次,true表示只会播放一次,false表示一直循环播放,内部用item节点声明一个动画帧,android:drawable指定此帧动画所对应的图片资源,android:druation表明此帧持续的时间,整数,单位为毫秒。api
注意:eclipse
以前使用eclipse或者Android ADT开发的时候,文件能够放在res/anim和res/drawable两个文件夹下面,虽然谷歌推荐放在res/drawable文件夹下可是不会报错,在使用Android studio时候就没那么幸运了,若是不放在res/drawable文件夹下面会报以下错误:布局
<ImageView android:id="@+id/animation_iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_margin="10dp" android:src="@drawable/lottery_animlist" />
这个时候咱们运行一下,发现动画没有运行而是停留在第一帧,那是由于AnimationDrawable播放动画是依附在window上面的,而在Activity onCreate方法中调用时Window还未初始化完毕,全部才会停留在第一帧,要想实现播放必须在onWindowFocusChanged中添加以下代码:post
imageView.setImageResource(R.drawable.lottery_animlist);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable(); animationDrawable.start();
若是想要中止播放动画能够调用AnimationDrawable的stop方法动画
imageView.setImageResource(R.drawable.lottery_animlist);
AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable(); animationDrawable.stop();
AnimationDrawable anim = new AnimationDrawable(); for (int i = 1; i <= 6; i++) { int id = getResources().getIdentifier("lottery_" + i, "mipmap", getPackageName()); Drawable drawable = getResources().getDrawable(id); anim.addFrame(drawable, 200); } anim.setOneShot(false); imageView.setImageDrawable(anim); anim.start();
void start()
- 开始播放动画spa
void stop()
- 中止播放动画code
addFrame(Drawable frame, int duration)
- 添加一帧,并设置该帧显示的持续时间
void setOneShoe(boolean flag)
- false为循环播放,true为仅播放一次
boolean isRunning()
- 是否正在播放
Frame Animation(逐帧动画)相对来讲比较简单,可是在实际开发中使用的频率仍是比较高的。但愿以这个小例子可以掌握逐帧动画,可是逐帧动画只能实现比较小的动画效果,若是复杂并且帧数比较多的动画不太建议使用逐帧动画,一方面是由于会形成OOM,另外一方面会显得很卡,若是真是超级复杂的动画的话建议选择双缓冲绘制View来实现。