2011-05-25 23:20:17
大家都知道,如果我们在Android中用ImageView直接显示GIF的图片,图片只会停在第一帧上,而不会继续。这时看到的只是一张静态的图片,没有GIF的效果。我们可以用Movie来显示图片 这个方法较简单;
1.在main.xml中添加ImageView,指定一张GIF图片为背景;
2.MainActivity.java
- package com.yin.displayGIF;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Movie;
- import android.os.Bundle;
- import android.view.View;
- public class MainActivity extends Activity {
- private MyCustomView mView;
- private Movie mMovie;
- private long mMovieStart;
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- mView = new MyCustomView(this);
- setContentView(mView);
- }
- //自定义一个类,继承View
- class MyCustomView extends View{
- public MyCustomView(Context context) {
- super(context);
- //以文件流的方式读取文件
- mMovie = Movie.decodeStream(
- getResources().openRawResource(R.drawable.my_picture));
- }
- @Override
- protected void onDraw(Canvas canvas) {
- long curTime = android.os.SystemClock.uptimeMillis();
- //第一次播放
- if(mMovieStart == 0){
- mMovieStart = curTime;
- }
- if(mMovie != null){
- int duration = mMovie.duration();
- int relTime = (int)((curTime - mMovieStart)% duration);
- mMovie.setTime(relTime);
- mMovie.draw(canvas, 0, 0);
- //强制重绘
- invalidate();
- }
- super.onDraw(canvas);
- }
- }
- }