Android支持GIF动画,但是如果利用ImageView标签直接写在布局文件中:
<ImageView android:id="@+id/gifpicture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/animation"/>
程序只能加载GIF动画的第一帧。效果如下:
如果想要正常播放GIF动画,需要借助Movie实现。写了一个简单示例,程序目录结构如下:
animation.gif是需要播放的GIF动画。
MainActivity实现了加载GIF动画的功能。
public class MainActivity extends Activity {
private Movie mMovie;
private long mMovieStart;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new CustomGifView(this));
}
class CustomGifView extends View {
public CustomGifView(Context context) {
super(context);
mMovie = Movie.decodeStream(getResources().openRawResource(
R.drawable.animation));
}
public void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now – mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, 0, 0);
invalidate();
}
}
}
}
内部类CustomGifView 利用Movie播放GIF动画。解释一下:
mMovie = Movie.decodeStream(getResources().openRawResource(R.drawable.animation));
将GIF动画以文件流的形式转换成Movie。
public void onDraw(Canvas canvas) {
long now = android.os.SystemClock.uptimeMillis();
if (mMovieStart == 0) { // first time
mMovieStart = now;
}
if (mMovie != null) {
int dur = mMovie.duration();
if (dur == 0) {
dur = 1000;
}
int relTime = (int) ((now – mMovieStart) % dur);
mMovie.setTime(relTime);
mMovie.draw(canvas, 0, 0);
invalidate();
}
}
invalidate();作用是刷新当前View,这样onDraw方法重复执行,Movie就能画出GIF动画的每一帧。到此,GIF动画就能正常播放了。