Android Glide应用中遇到问题

1. 导入库

build.gradle中添加glide库,kotlin用kapt,java用annotationProcessor

dependencies {
    implementation 'com.github.bumptech.glide:glide:4.13.2'
    kapt 'com.github.bumptech.glide:compiler:4.13.2'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.13.2'
}

ProjectGlideModule继承AppGlideModule,需要添加GlideModule注释。applyOptions方法中可以对builder进行全局配置。

@GlideModule
class ProjectGlideModule : AppGlideModule() {

    override fun applyOptions(context: Context, builder: GlideBuilder) {
        super.applyOptions(context, builder)
    }

    override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
        super.registerComponents(context, glide, registry)
    }
    
}

2. OKHttp配置

Glide 默认的请求网络框架是HttpURLConnection,想要改成OkHttp就需要用到registerComponents函数。首先需要导入okhttp3-integration

implementation 'com.github.bumptech.glide:okhttp3-integration:4.13.2'

registerComponents函数内调用Registryreplace方法替代网络请求框架。

override fun registerComponents(context: Context, glide: Glide, registry: Registry) {
    super.registerComponents(context, glide, registry)

    registry.replace(GlideUrl::class.java, InputStream::class.java, OkHttpUrlLoader.Factory(NetworkUtil.getOKHttpClient()))
}

3. 自定义模型

在实际项目中,我们往往会有一些特殊需要。比如我们通过url返回图片的字节流,还需要Base64解码才能使用。

  • 定义GlideDownloadPic类,继承com.bumptech.glide.load.Key,需要实现updateDiskCacheKey函数
    class GlideDownloadPic(val picUrl: String) : Key {
        private var mGlideUrl = GlideUrl(picUrl)
    
        override fun updateDiskCacheKey(messageDigest: MessageDigest) {
            mGlideUrl.updateDiskCacheKey(messageDigest)
        }
    
    }
    
  • 定义GlideDownloadPicModelLoader,继承ModelLoaderFactory继承ModelLoaderFactory,在后面注册时使用。buildLoadData函数用来获取图片数据。
    class GlideDownloadPicModelLoader : ModelLoader<GlideDownloadPic, InputStream> {
    
        class Factory : ModelLoaderFactory<GlideDownloadPic, InputStream> {
    
            override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<GlideDownloadPic, InputStream> {
                return GlideDownloadPicModelLoader()
            }
    
            override fun teardown() {
            }
    
        }
    
        override fun buildLoadData(
            model: GlideDownloadPic,
            width: Int,
            height: Int,
            options: Options
        ): ModelLoader.LoadData<InputStream>? {
            return ModelLoader.LoadData(model, GlideDownloadPicDataFetcher(model))
        }
    
        override fun handles(model: GlideDownloadPic): Boolean {
            return true
        }
    
    }
    
  • 定义GlideDownloadPicDataFetcher,继承DataFetcher
    class GlideDownloadPicDataFetcher(downloadPic: GlideDownloadPic) : DataFetcher<InputStream> {
    
        private var mDownloadPic = downloadPic
    
        override fun loadData(priority: Priority, callback: DataFetcher.DataCallback<in InputStream>) {
            downloadPic(mDownloadPic.picUrl, {
                callback.onDataReady(ByteArrayInputStream(Base64.decode(it, Base64.DEFAULT)))
            }, {
                callback.onLoadFailed(it)
            })
        }
    
        // 下载图片
        private fun downloadPic(picUrl: String, onSuccess:(ByteArray) -> Unit, onFail:(Exception) -> Unit) {
            if (picUrl.startsWith("http")) {
                NetworkUtil.getOKHttpClient()
                    .newCall(Request.Builder().url(picUrl).build())
                    .enqueue(object : Callback{
                        override fun onResponse(call: Call, response: Response) {
                            if (response.isSuccessful) {
                                var bodyByteArray = response.body()?.bytes()
                                if (bodyByteArray != null) {
                                    onSuccess(bodyByteArray)
                                    return
                                }
                            }
                            onFail(IOException("wrong url $picUrl"))
                        }
    
                        override fun onFailure(call: Call, e: IOException) {
                            onFail(IOException("wrong url $picUrl"))
                        }
                    })
            } else {
                onFail(IOException("wrong url $picUrl"))
            }
        }
    
        override fun getDataClass(): Class<InputStream> {
            return InputStream::class.java
        }
    
        override fun cleanup() {
        }
    
        override fun getDataSource(): DataSource {
            return DataSource.REMOTE
        }
    
        override fun cancel() {
        }
    }
    
  • registerComponents函数内注册
    registry.replace(GlideDownloadPic::class.java, InputStream::class.java,
            GlideDownloadPicModelLoader.Factory())
    
  • 使用自定义模型
    Glide.with(this).load(GlideDownloadPic("xxx.jpg"))
            .error(getDrawable(R.drawable.xxx))
            .into(findViewById(R.id.image_view))
    

你可能感兴趣的:(Android,图像动画,android,glide)