很久没有写东西了,手有点生疏了,项目中有可能用到gif图片的话,直接拿去用就好了,懒得多说自己去看效果
main.xml
<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"
>
<com.example.csa.GifView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="20dp" />
</RelativeLayout>
MyGifView.class
package com.example.csa;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.util.AttributeSet;
import android.view.View;
public class GifView extends View {
//表示开始播放gif图片的绝对时间
private long movieStart = 0;
//movie对象管理gif图片里面的多个帧
private Movie movie;
public GifView(Context context, AttributeSet attrs) {
super(context, attrs);
movie = Movie.decodeStream(context.getResources().openRawResource(
R.raw.media_gif));
}
@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);
}
}
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
值得注意的是manifest.xml
如果targetSdkVersion>13的时候gif不能在正常显示效果