1,解决Glide加载Gif非常慢问题
Glide.with(MainActivity.this).load(url).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(imageView);
为其添加缓存策略,其中缓存策略可以为:Source及None,None及为不缓存,Source缓存原型.如果为ALL和Result就不行
2,加载第一贞:
Glide.with(context).load(gifUrl).asBitmap().into(imageViewGifAsBitmap);
3,控制动画次数:
Glide.with(this).load(getResource()).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(new GlideDrawableImageViewTarget(imageView, 1));
4,GIF 时间
3.x版本
Glide.with(FirstActivity.this)
.load(file)
.asGif()
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.listener(new RequestListener<File, GifDrawable>() {
@Override
public boolean onException(Exception e, File model, Target<GifDrawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(final GifDrawable resource, File model, Target<GifDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
new Thread(new Runnable() {
@Override
public void run() {
int duration = 0;
try {
GifDrawable gifDrawable = (GifDrawable) resource;
GifDecoder decoder = gifDrawable.getDecoder();
for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
duration += decoder.getDelay(i);
}
mGifAdTime = duration;
} catch (Throwable e) {
}
}
}).start();
return false;
}
})
.into(mAdImg);
4.x版本获取gif动画时长
private int getGifTime(GifDrawable resource) {
// 计算动画时长
int duration = TIME;
try {
GifDrawable gifDrawable = resource;
//设置循环播放次数为1次
int time = 0;
gifDrawable.setLoopCount(1);
//GifDecoder decoder = gifDrawable.getDecoder();//4.0开始没有这个方法了
Drawable.ConstantState state = gifDrawable.getConstantState();
if (state != null) {
//不能混淆GifFrameLoader和GifState类
Object gifFrameLoader = GlideGifUtil.getValue(state, "frameLoader");
if (gifFrameLoader != null) {
Object decoder = GlideGifUtil.getValue(gifFrameLoader, "gifDecoder");
if (decoder != null && decoder instanceof GifDecoder) {
for (int i = 0; i < gifDrawable.getFrameCount(); i++) {
time += ((GifDecoder) decoder).getDelay(i);
}
}
}
duration = time;
}
} catch (Throwable e) {
}
return duration;
}
获取gif时长工具类
public class GlideGifUtil {
/**
* 通过字段名从对象或对象的父类中得到字段的值
*
* @param object 对象实例
* @param fieldName 字段名
* @return 字段对应的值
* @throws Exception
*/
public static Object getValue(Object object, String fieldName) throws Exception {
if (object == null) {
return null;
}
if (TextUtils.isEmpty(fieldName)) {
return null;
}
Field field = null;
Class<?> clazz = object.getClass();
for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
try {
field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
} catch (Exception e) {
//这里甚么都不要做!并且这里的异常必须这样写,不能抛出去。
//如果这里的异常打印或者往外抛,则就不会执行clazz = clazz.getSuperclass(),最后就不会进入到父类中了
}
}
return null;
}
}