Android显示GIF图片

今天我们研究一下怎样在Android手机上显示GIF动态图片
首先须要在src文件夹下新建一个自己定义的View。代码例如以下:

</pre><pre name="code" class="java">
</pre><pre name="code" class="java">

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;

public class MyGifView extends View {
	
	//表示開始播放gif图片的绝对时间
	private long movieStart = 0;
	//movie对象管理gif图片里面的多个帧
	private Movie movie;

	public MyGifView(Context context, AttributeSet attrs) {
		super(context, attrs);
		movie = Movie.decodeStream(context.getResources().openRawResource(
				R.drawable.horse));
	}

	@Override
	protected void onDraw(Canvas canvas) {
		long currentTime = System.currentTimeMillis();
		// 第一次播放
		if (movieStart == 0) {
			movieStart = currentTime;
		}
		
		//循环播放
		if (movie != null) {
			int duration = movie.duration();
			int relTime = (int) ((currentTime - movieStart) % duration);
			movie.setTime(relTime);
			movie.draw(canvas, 0, 0);
			// 强制重绘
			invalidate();
		}
		
		//假设仅仅想播放一次,仅仅需推断currentTime-movieStart的值大于duration就不重绘就可以

		super.onDraw(canvas);
	}
}

接着写一个Activity,用来显示gif图片:

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
}

XML布局文件是:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <com.example.gifdemo.MyGifView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp" />

</RelativeLayout>

效果图例如以下:



整个演示样例project文件下载链接:

Android显示GIF图片


posted @ 2016-02-04 13:31  mengfanrong  阅读(330)  评论(0编辑  收藏  举报