Android中轻松显示Gif图片
大家都知道,Android开发模拟器为了节省内存,一般不支持直接显示gif图片,即使你强制设置了,也只会显示图片的第一帧。看到网上也有许多的方法,来实现此功能,可都比较的繁琐,需要修改android源代码来实现或者用gif解析器来实现。在此文章中,这里教大家一种比较简洁的一个方法,你可以把这个类当做是一种工具类。用的时候,直接搬到程序里面,更改下图片的资源,就可以非常轻松的显示gif图片了。
步骤1:看一下这个工具类的实例代码:MyGifView.java
1 import android.content.Context; 2 import android.graphics.Canvas; 3 import android.graphics.Movie; 4 import android.util.AttributeSet; 5 import android.util.Log; 6 import android.view.View; 7 8 public class MyGifView extends View{ 9 private long movieStart; 10 private Movie movie; 11 //此处必须重写该构造方法 12 public MyGifView(Context context,AttributeSet attributeSet) { 13 super(context,attributeSet); 14 //以文件流(InputStream)读取进gif图片资源 15 movie=Movie.decodeStream(getResources().openRawResource(R.drawable.view)); 16 } 17 18 @Override 19 protected void onDraw(Canvas canvas) { 20 long curTime=android.os.SystemClock.uptimeMillis(); 21 //第一次播放 22 if (movieStart == 0) { 23 movieStart = curTime; 24 } 25 if (movie != null) { 26 int duraction = movie.duration(); 27 if(duraction == 0){ 28 duraction = 15000; 29 } 30 int relTime = (int) ((curTime-movieStart)%duraction); 31 movie.setTime(relTime); 32 movie.draw(canvas, 0, 0); 33 34 //强制重绘 35 invalidate(); 36 } 37 super.onDraw(canvas); 38 } 39 40 }
此工具类中,只做了2件事情。1,构造方法;2,重写了onDraw()方法。大家以后用的话,只需拷贝此类到你的工程下即可起作用。
步骤2:布局文件代码 activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:text="====Gif图片测试布局====" android:layout_height="wrap_content" android:layout_width="wrap_content"/> <com.example.rungif.MyGifView android:id="@+id/iv" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_margin="20dp"/> </LinearLayout>
步骤3:主activity中调用
1 public class MainActivity extends Activity { 2 @Override 3 protected void onCreate(Bundle savedInstanceState) { 4 super.onCreate(savedInstanceState); 5 setContentView(R.layout.main); 6 7 } 8 }
到此便完成了