第一种:使用Fresco的SimpleDraweeView来显示GIF
1、在布局文件中加入命名空间:
< ?xml version=”1.0” encoding=”utf-8”?>
< RelativeLayout xmlns:android=”http://schemas.android.com/apk/res/android”
xmlns:fresco=”http://schemas.android.com/apk/res-auto”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_alignParentTop=”true”>
2、在布局中加入SimpleDraweeView:
< com.facebook.drawee.view.SimpleDraweeView
android:id=”@+id/view”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
fresco:actualImageScaleType=”focusCrop”
fresco:failureImage=”@mipmap/icon_failure”
fresco:failureImageScaleType=”centerInside”/>
3、初始化Fresco类:
ImagePipelineConfig config = ImagePipelineConfig.newBuilder(mContext)
.setDownsampleEnabled(true)
.build();
Fresco.initialize(mContext, config);//初始化显示GIF控件
4、开始加载GIF
private void showGif(SimpleDraweeView view, int id) {
Uri uri = new Uri.Builder()
.scheme(UriUtil.LOCAL_RESOURCE_SCHEME) // "res"
.path(String.valueOf(id))
.build();
ControllerListener<ImageInfo> controllerListener = new BaseControllerListener<ImageInfo>() {
@Override
public void onFinalImageSet(
String id,
@Nullable ImageInfo imageInfo,
@Nullable Animatable anim) {
if (anim != null) {
anim.start();
}
}
};
AbstractDraweeControllerBuilder abs = Fresco.newDraweeControllerBuilder()
.setAutoPlayAnimations(false)
.setControllerListener(controllerListener)
.setUri(uri);
DraweeController animatedGifController = abs.build();
view.setController(animatedGifController);
}
注:我这的gif是放入在mipmap里边的名称是test.gif,直接R.mipmap.test传入这个方法就行。
5、在gradle中添加依赖:
compile 'com.facebook.fresco:fresco:0.10.0'
compile 'com.facebook.fresco:animated-gif:0.10.0'
compile 'com.facebook.fresco:animated-base-support:0.10.0'
第二种:使用Glide来显示GIF
1、在布局文件中只用用ImageView:
< ImageView
android:id=”@+id/gif_iv”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:layout_centerInParent=”true”
android:contentDescription=”@string/app_name”/>
2、使用Glide来加载GIF:
Glide.with(this).load(R.mipmap.test).into(new GlideDrawableImageViewTarget(gif_glide));
注:默认是一直重复播放的,如果想指定播放次数则按照下面的写:
Glide.with(this).load(R.mipmap.test).into(new GlideDrawableImageViewTarget(gif_glide,3));
3、在gradle里边添加Glide依赖:
compile ‘com.github.bumptech.glide:glide:3.6.1’
完成