在查阅了所有Glide文档和StackOverflow的问题与答案后,我没有找到任何关于如何在Glide 4中为单个Glide调用应用资源解码器的信息。
在Glide 3中我们可以这样做:
Glide.with(imagePreview.context)
.load(mediaItem.path)
.asBitmap()
.decoder(decoderWithDownSampleAtMost(imagePreview.context))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(false)
.dontAnimate()
.into(target)
private fun decoderWithDownSampleAtMost(ctx: Context): GifBitmapWrapperResourceDecoder {
return GifBitmapWrapperResourceDecoder(
ImageVideoBitmapDecoder(StreamBitmapDecoder(Downsampler.AT_MOST,
Glide.get(ctx).bitmapPool,
DecodeFormat.DEFAULT),
FileDescriptorBitmapDecoder(ctx)),
GifResourceDecoder(ctx),
Glide.get(ctx).bitmapPool)
}
在版本4中,我知道我们可以使用AppGlideModule
来自定义ResourceDecoder
@GlideModule
class MyAppGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.prepend(String::class.java, Bitmap::class.java, GalleryDecoder(context))
}
}
然而,这适用于所有 Glide 调用。如何使 ResourceDecoder
像 v3 一样,能够应用于单个调用?更新:在咨询了这里的 Glide Github Issues
之后,我能够想出一个解决方案: https://github.com/bumptech/glide/issues/3522
基本上,我需要创建一个自定义的 Option
并使用它来确定是否触发我的自定义 ResourceDecoder
。 这是我的示例:
- 普通的
AppGlideModule
@GlideModule
class MyAppGlideModule : AppGlideModule() {
override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
registry.prepend(Any::class.java, Bitmap::class.java, MainActivity.GalleryDecoder(context, glide.bitmapPool))
}
}
- 在我的
Activity
中:
class MainActivity : AppCompatActivity() {
companion object {
val GALLERY_DECODER: Option<Boolean> = Option.memory("abc")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
GlideApp.with(this)
.asBitmap()
.load("link_or_path_here")
.apply(option(GALLERY_DECODER, true))
.into(image_view)
}
}
- 我的
GalleryDecoder
:
open class GalleryDecoder(
private val context: Context,
private val bitmapPool: BitmapPool
) : ResourceDecoder<Any, Bitmap> {
override fun decode(source: Any, width: Int, height: Int, options: Options): Resource<Bitmap>? {
return BitmapResource.obtain(BitmapFactory.decodeResource(context.resources, R.drawable.giphy), bitmapPool)
}
override fun handles(source: Any, options: Options): Boolean = options.get(GALLERY_DECODER) ?: false
}
如果您不想使用 GalleryDecoder
,只需从 Glide 加载中删除 .apply(option(GALLERY_DECODER, true))
即可。祝好!
Class<T>
表示常见资源类型,如Drawable
、Bitmap
,而不是ResourceDecoder
。 - Bach VuGlide
代码时,我注意到我们可以使用自定义的buckets
(标识符)进行registry.prepend
,但仍在寻找实现此操作的方法。 - Bach Vu