用Movie显示gif(1)SimpleGif

 

代码如下:

 1 import android.content.Context;
 2 import android.graphics.Canvas;
 3 import android.graphics.Movie;
 4 import android.os.Build;
 5 import android.util.AttributeSet;
 6 import android.view.View;
 7 
 8 import com.e.weixin.R;
 9 
10 public class SimpleGif extends View {
11 
12     private Movie movie;        //播放动画的类
13     private long firstFrame;    //第1帧的时间
14 
15     public int gifId;           //gif的res
16     public int times;           //循环次数
17     public int currentFrame;    //当前播放到第几帧
18     public int duration;        //动画时长
19 
20 
21     public SimpleGif(Context context, AttributeSet attrs) {
22         super(context, attrs);
23         boolean b = isHardwareAccelerated();
24         //在有的版本上要关闭硬件加速才显示动画,
25         //也可以在manifest.xml的application,activity等元素下用android:hardwareAccelerated="false" 关闭硬件加速。
26         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
27             setLayerType(View.LAYER_TYPE_SOFTWARE, null);
28         }
29         b = isHardwareAccelerated();
30         gifId = R.raw.tsj01;
31         //构造一个movie
32         movie = Movie.decodeStream(getResources().openRawResource(gifId));
33         duration = movie.duration();//动画的总共时长
34         if (duration == 0) { //设置一个默认时间
35             duration = 1000;
36         }
37         times = 1;
38     }
39 
40     public void onDraw(Canvas canvas) {
41 
42         //绘制第1步,取得当前时间
43         long now = android.os.SystemClock.uptimeMillis();
44 
45         //记录第1帧的时间
46         if (firstFrame == 0) {// first time
47             firstFrame = now;
48         }
49 
50         if (movie != null) {
51             //如果循环次数不为0就断续绘制。
52             if (times > 0) {
53                 //计算当前帧的时间
54                 currentFrame = (int) (now - firstFrame);
55                 //如果当前帧大于时长,就说明是新循环开始
56                 if (currentFrame > duration){
57                     --times;//循环次数减1
58                     firstFrame = now;
59                     //计算在动画时长内的帧。
60                     currentFrame %= duration;
61                     System.out.println(" 倒数第  " + times + "");
62                 }
63                 //设置当前绘制的帧
64                 movie.setTime(currentFrame);
65 
66                 //开始绘制动画的当前帧
67                 movie.draw(canvas, 0, 0);
68 
69                 //刷新,绘制下1帧
70                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
71                     postInvalidateOnAnimation();
72                 } else {
73                     invalidate();
74                 }
75             }else{
76                 movie.setTime(0);//设置绘制第0帧
77                 movie.draw(canvas, 0, 0);//绘制
78             }
79         }
80     }
81 
82 }

 

posted @ 2016-07-07 15:01  f9q  阅读(226)  评论(0编辑  收藏  举报