你的位置:首页 > 操作系统

[操作系统]让ImageView可以使用gif的方法


在自己的包中添加MyGifView.java(直接复制,粘贴),读取gif资源在MyGifView中第20行读取:

MyGifView.java:

 1 package com.zzw.testgifuseimageview; 2  3 import android.content.Context; 4 import android.graphics.Canvas; 5 import android.graphics.Movie; 6 import android.util.AttributeSet; 7 import android.view.View; 8  9 10 public class MyGifView extends View {11 12   private long movieStart;13   private Movie movie;14 15   // 重写该构造方法16   public MyGifView(Context context, AttributeSet attributeSet) {17     super(context, attributeSet);18 19     // 以文件流(InputStream)读取进gif图片资源20     movie = Movie.decodeStream(getResources().openRawResource(R.drawable.test));21   }22 23   @Override24   protected void onDraw(Canvas canvas) {25     26     long curTime = android.os.SystemClock.uptimeMillis();27     28     // 第一次播放29     if (movieStart == 0) {30       movieStart = curTime;31     }32     if (movie != null) {33       int duraction = movie.duration();34       int relTime = (int) ((curTime - movieStart) % duraction);35       movie.setTime(relTime);36       movie.draw(canvas, 0, 0);37       // 强制重绘38       invalidate();39     }40     41     super.onDraw(canvas);42   }43 }

 

把要放gif图片的ImageView的名字改为  包名.MyGifView

<RelativeLayout ="http://schemas.android.com/apk/res/android"  ="http://schemas.android.com/tools"  android:layout_width="match_parent"  android:layout_height="match_parent"  tools:context="com.zzw.testgifuseimageview.MainActivity" >  <com.zzw.testgifuseimageview.MyGifView    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_margin="20dp" /></RelativeLayout>

MainActivity.java:

 1 package com.zzw.testgifuseimageview; 2  3 import android.app.Activity; 4 import android.os.Bundle; 5  6 public class MainActivity extends Activity { 7  8   @Override 9   protected void onCreate(Bundle savedInstanceState) {10     super.onCreate(savedInstanceState);11     setContentView(R.layout.activity_main);12   }13 }