<span style="font-family: KaiTi_GB2312; background-color: rgb(255, 255, 255);">今天我们研究一下如何在Android手机上显示GIF动态图片。</span>
首先需要在src目录下新建一个自定义的View,代码如下:
import android.content.Context; import android.graphics.Canvas; import android.graphics.Movie; import android.util.AttributeSet; import android.view.View; public class MyGifView extends View { //表示开始播放gif图片的绝对时间 private long movieStart = 0; //movie对象管理gif图片里面的多个帧 private Movie movie; public MyGifView(Context context, AttributeSet attrs) { super(context, attrs); movie = Movie.decodeStream(context.getResources().openRawResource( R.drawable.horse)); } @Override protected void onDraw(Canvas canvas) { long currentTime = System.currentTimeMillis(); // 第一次播放 if (movieStart == 0) { movieStart = currentTime; } //循环播放 if (movie != null) { int duration = movie.duration(); int relTime = (int) ((currentTime - movieStart) % duration); movie.setTime(relTime); movie.draw(canvas, 0, 0); // 强制重绘 invalidate(); } //如果只想播放一次,只需判断currentTime-movieStart的值大于duration就不重绘即可 super.onDraw(canvas); } }
import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } }
<RelativeLayout 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" tools:context="${relativePackage}.${activityClass}" > <com.example.gifdemo.MyGifView android:id="@+id/iv" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="20dp" /> </RelativeLayout>
整个示例工程文件下载链接:
原文:http://blog.csdn.net/bear_huangzhen/article/details/38366701