Android支持GIF动画,但是如果利用ImageView标签直接写在布局文件中:
<
ImageView
android:id=
"@+id/gifpicture"
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:src= "@drawable/animation" />
android:layout_width= "fill_parent"
android:layout_height= "wrap_content"
android:src= "@drawable/animation" />
程序只能加载GIF动画的第一帧。效果如下:

如果想要正常播放GIF动画,需要借助Movie实现。写了一个简单示例,程序目录结构如下:

animation.gif是需要播放的GIF动画。
MainActivity实现了加载GIF动画的功能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
publicclass MainActivity
extends
Activity {
private
Movie mMovie;
privatelong mMovieStart;
/** Called when the activity is first created. */
@Override
publicvoid 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));
}
publicvoid 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();
}
}
}
}
|
mMovie = Movie.decodeStream(getResources().openRawResource(R.drawable.animation));
将GIF动画以文件流的形式转换成Movie。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
publicvoid 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动画就能正常播放了。
还有一种方法是根据配置文件,设置播放帧,显然是不推荐的。当然想了解,请看 http://developer.aiwgame.com/