android 通过帧动画方式播放Gif动画

注意:经过本人测试,这个方法很耗内存, 图片一多就崩了.慎用

<1>用工具(photoshop或者FireWorks)将GIF动画图片分解成多个GIF静态图片,然后保存在resdrawable目录下。

<2>在resanim目录下定义这些GIF静态图片(假设将GIF动态图片分解成6个图片,anim1.gif....anim6.gif)。在frame_animation.xml文件中定义这些GIF文件,如下:

<animation-list  xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
 <item android:drawable="@drawable/anim1" android:duration="50"/>
 <item android:drawable="@drawable/anim2" android:duration="50"/>
 <item android:drawable="@drawable/anim3" android:duration="50"/>
 <item android:drawable="@drawable/anim4" android:duration="50"/>
 <item android:drawable="@drawable/anim5" android:duration="50"/>
 <item android:drawable="@drawable/anim6" android:duration="50"/>

</animation-list>

android:oneshot = false表示无限播放,为true时,表示播放一次。

<3>编写完动画文件后,就需要装载动画文件,并创建AnimationDrawable对象。

 AnimationDrawable anim = (AnimationDrawable) getResources().getDrawable(R.anim.frame_animation);

创建完AnimationDrawable对象后,可以将该对象做为ImageView组件的背景

ImageView image = (ImageView) findViewById(R.id.image);

image.setBackgroundDrawable(anim);

除了上面的装载方式外,还有别的装载方式:

ImageView image = (ImageView) findViewById(R.id.image);

image.setBackgroundResource(R.anim.frame_animation);

Object backgroundObject = image.getBackground();

AnimationDrawable anim = (AnimationDrawable) backgroundObject;

AnimationDrawable类中与帧动画相关的方法有:

start:开始播放帧动画。

stop:停止播放帧动画。

setOneShot:设置动画只播放一次。为true是表示只播放一次。

addFrame:向AnimationDrawable对象中添加新的帧。

isOneShot:判断是否只播放一次。

getNumberOfFrames:返回动画的帧数。

getFrame:根据帧索引获得指定帧的Drawable对象。帧从0开始。

getDuration:获得指定帧的停留时间。

setAlpha:设置帧的透明度。

原文地址:https://www.cnblogs.com/mafeng/p/5241893.html