/**
* 设置圆形new CircleCrop(),这里可以根据不同需求自定义圆角
*/
Glide.with(this).load(url).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(new CustomTarget
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition super Drawable> transition) {
user_head_photo.setImageDrawable(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
//从任何视图中删除onResourceReady中提供的绘图,并确保没有对它的任何引用。
}
});
/**
* Gif 加载 可以设置次数,监听播放完成回调
* @param context 上下文对象
* @param model 传入的gif地址,可以是网络,也可以是本地,
* @param imageView 要显示的imageView
* @param loopCount 播放次数
* @param gifListener Gif播放完毕回调
*/
public void loadGif(Context context, Object model, final ImageView imageView, int loopCount, final GifListener gifListener){
Glide.with(context).asGif().load(model).listener(new RequestListener() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(GifDrawable resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
try {
Field gifStateField = GifDrawable.class.getDeclaredField("state");
gifStateField.setAccessible(true);
Class gifStateClass = Class.forName("com.bumptech.glide.load.resource.gif.GifDrawable$GifState");
Field gifFrameLoaderField = gifStateClass.getDeclaredField("frameLoader");
gifFrameLoaderField.setAccessible(true);
Class gifFrameLoaderClass = Class.forName("com.bumptech.glide.load.resource.gif.GifFrameLoader");
Field gifDecoderField = gifFrameLoaderClass.getDeclaredField("gifDecoder");
gifDecoderField.setAccessible(true);
Class gifDecoderClass = Class.forName("com.bumptech.glide.gifdecoder.GifDecoder");
Object gifDecoder = gifDecoderField.get(gifFrameLoaderField.get(gifStateField.get(resource)));
Method getDelayMethod = gifDecoderClass.getDeclaredMethod("getDelay", int.class);
getDelayMethod.setAccessible(true);
////设置播放次数
resource.setLoopCount(loopCount);
//获得总帧数
int count = resource.getFrameCount();
int delay =0;
for (int i =0; i < count; i++) {
//计算每一帧所需要的时间进行累加
delay += (int) getDelayMethod.invoke(gifDecoder, i);
}
imageView.postDelayed(() -> {
if (gifListener !=null) {
gifListener.gifPlayComplete();
}
}, delay +200);//设置动画加载完停留最后一贞200毫秒
}catch (NoSuchFieldException | InvocationTargetException | NoSuchMethodException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
return false;
}
}).into(imageView);
}
/**
* Gif播放完毕回调
*/
public interface GifListener {
void gifPlayComplete();
}
}
}