Android中播放Gif图片的方法。
主要原理是取出Gif中的每一帧图片,分别设置到ImageView上边展示出来
使用到Code.Google上边的一个开源类库GifDecoder,下载不了的可以从我后边给出的Demo中搬运。
准备一个类继承自ImageView重写其构造方法同时传入一个输入流。
<span style="font-size:18px;">public class GifDecoderView extends ImageView</span>
<span style="font-size:18px;">public GifDecoderView(Context context, InputStream is) {
super(context);
playGif(is);
}</span>
playGif是播放Gif图片的主要方法,稍后给出。
在我们新建的类中增加5个参数,一个Boolean型变量去表示我们用来播放gif图片的线程是不是运行状态,一个GifDecoder的实例,一个bitmap对象用来储存这个动画的每一帧图像,一个handler去更新UI线程的信息,一个Runnable实例用来处理画出我们刚刚定义的bitmap的事情。
<span style="font-size:18px;"><span style="white-space:pre"> </span>private boolean isAni;
private GifPlayer gp;
private Bitmap bm;
private Handler handler = new Handler();
private Runnable playFrame = new Runnable() {
@Override
public void run() {
if (null != bm && !bm.isRecycled()) {
GifDecoderView.this.setImageBitmap(bm);
}
}
};</span>
Runnable对象中包含的是更新界面图片的方法。
playGif方法:
<span style="font-size:18px;">private void playGif(InputStream is) {
gp = new GifPlayer();
gp.read(is);
isAni = true;
new Thread() {
public void run() {
final int frameCount = gp.getFrameCount();
final int loopCount = gp.getLoopCount();
do {
for (int i = 0; i < frameCount; i++) {
bm = gp.getFrame(i);
int t = gp.getDelay(i);
handler.post(playFrame);
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} while (true);
};
}.start();
}</span>
新建一个activity引用我们自定义好的GifdecoderView,传入要显示的Gif图片
这里我是再assets目录中放入了一个Gif图片
<span style="font-size:18px;"><span style="white-space:pre"> </span>InputStream is = null;
try {
is = getAssets().open("7.gif");
} catch (IOException e) {
e.printStackTrace();
}
GifDecoderView view = new GifDecoderView(this, is);
setContentView(view);</span>
至此Gif图片就可以播放出来了。