Glide加載圖檔非常友善,使用也非常廣泛,但是并不能直接支援webp動圖。
可能很多人會使用Fresco來加載webp,但是對于已經使用Glide的項目,總感覺再使用Fresco有點備援,如果能用Glide來加載webp那将非常友善。
而github上也确實存在webpdecoder這樣一個庫支援加載webp。
具體使用方式總結如下:
一、首先加入依賴
//Glide庫
//implementation 'com.github.bumptech.glide:glide:4.7.1'//support
implementation 'com.github.bumptech.glide:glide:4.12.0'//androidx
annotationProcessor "com.github.bumptech.glide:compiler:4.12.0"//androidx
//Glide支援webp動圖的庫
implementation "com.github.zjupure:webpdecoder:2.0.4.12.0"
二、使用
使用方法跟Glide的使用非常相似
//webp動圖
Transformation<Bitmap> transformation = new CenterInside();
Glide.with(mAnimView)
.load(R.drawable.webp_anim)//不是本地資源就改為url即可
.optionalTransform(transformation)
.optionalTransform(WebpDrawable.class, new WebpDrawableTransformation(transformation))
.into(mAnimView);
三、動畫播放完成監聽
關于動畫播放完成的監聽,網上也有做法是通過反射拿到webp每一幀動畫的時間,再累加起來得到動畫總時長,最後通過Handler的postDelay進行延遲作為動畫播放結束的回調,這樣想想就知道不是很精确,如果誤差可以接受那就可以。
監聽其實就是在資源加載成功的回調裡面,對WebpDrawable進行監聽,不過要注意webp的循環次數如果是無限循環,那将不會有結束回調,可以通過代碼設定循環次數為有限的即可。
為什麼我知道是通過WebpDrawable進行監聽,因為我之前用過Fresco,它的監聽大概這樣:
animatedDrawable.setAnimationListener(...)
是以我猜到了。其實進去WebpDrawable類裡面看看,就知道它其實也實作了這麼個接口
而Animatable2Compat接口就有結束的接方法。
是以動畫播放完成回調的做法如下,隻不過在上面的做法加多一點代碼而已:
//webp動圖
Transformation<Bitmap> transformation = new CenterInside();
Glide.with(mAnimView)
.load(R.drawable.webp_anim)//不是本地資源就改為url即可
.optionalTransform(transformation)
.optionalTransform(WebpDrawable.class, new WebpDrawableTransformation(transformation))
.addListener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
WebpDrawable webpDrawable = (WebpDrawable) resource;
//需要設定為循環1次才會有onAnimationEnd回調
webpDrawable.setLoopCount(1);
webpDrawable.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
@Override
public void onAnimationStart(Drawable drawable) {
super.onAnimationStart(drawable);
}
@Override
public void onAnimationEnd(Drawable drawable) {
super.onAnimationEnd(drawable);
webpDrawable.unregisterAnimationCallback(this);
}
});
return false;
}
})
.into(mAnimView);