一、说明
Glide 可以加载 2 种动图,一种是 Gif 图,另一种是 Webp 动图。
有时候我们需要获取动图的第一帧,并以封面的形式显示,那该怎样获取呢?
二、获取 Webp 第一帧
我这儿的 Webp 显示用到了一个三方库:
"com.github.zjupure:webpdecoder:2.3.$glideVersion"
获取第一帧:
Glide.with(context).asDrawable().load(url)
.optionalTransform(WebpDrawable.class, new WebpDrawableTransformation(new CenterCrop()))
.into(new CustomTarget<Drawable>() {
@Override
public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
if (resource instanceof WebpDrawable) {
// 从 webp 图片中获取第一帧
WebpDrawable webpDrawable = (WebpDrawable) resource;
Bitmap bitmap = webpDrawable.getFirstFrame();
}
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {}
});
三、获取 Gif 第一帧
场景 1:直接显示到 ImageView
Glide.with(context)
.setDefaultRequestOptions(new RequestOptions().frame(1))
.load(url)
.into(imageView);
可以通过 setDefaultRequestOptions(new RequestOptions().frame(1)) 来设置获取第一帧。
场景 2:获取第一帧 bitmap
Glide.with(context)
.asBitmap()
.load(url)
.into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
// resource 即为第一帧的图片
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
请求 Gif 的时候我们用 bitmap 接收,Glide 发现目标类型无法承载整个 Gif 资源,就会拿第一帧给你,这样你也就获取到了第一帧。