Coil - Android开源图像加载库
Coil是一个开源的图像加载库,用于在Android中显示网络或本地图像资源。
为什么我们使用Coil?
- 快速:Coil进行了许多优化,包括内存和磁盘缓存、内存中的图像降采样、自动暂停/取消请求等。
- 轻量级:对于已经使用OkHttp和协程的应用程序来说,Coil会向您的APK添加大约2000个方法,与Picasso相当,明显少于Glide和Fresco。
- 易于使用:Coil的API利用了Kotlin的语言特性,简洁而少量的样板代码。
- 现代化:Coil以Kotlin为主,并使用包括协程、OkHttp、Okio和AndroidX Lifecycles在内的现代化库。
我们如何使用Coil?
-
通过将以下行添加到模块级
build.gradle
文件中,将Coil库引入项目。implementation("io.coil-kt:coil:2.5.0")
-
使用扩展函数是使用Coil加载图像的最简单方法。
// 使用URL加载图像imageView.load("https://example.com/image.jpg")// 使用文件加载图像imageView.load(File("/path/to/image.jpg"))// 从Android资源(drawable)中加载图像imageView.load(R.drawable.person)
- 我们可以自定义请求
imageView.load("https://example.com/image.jpg") { crossfade(true)crossfade(500)placeholder(R.drawable.person)}
创建自定义图像加载器
我们可以根据项目需求创建一个自定义图像加载器。如果我们不创建一个新的加载器,Coil将使用其内置的图像加载器以及默认选项。
class MainApplication : Application(), ImageLoaderFactory {override fun newImageLoader(): ImageLoader {return ImageLoader.Builder(this.applicationContext).crossfade(true).build()}
}
为图像加载器添加日志拦截器
创建一个自定义的日志类,它扩展了Interceptor并实现所需的方法。
class CoilLoggingInterceptor : Interceptor {companion object {val TAG: String = CoilLoggingInterceptor::class.java.simpleName}override suspend fun intercept(chain: Interceptor.Chain): ImageResult {val logModel = CoilLogModel(url = chain.request.data.toString(),width = chain.size.width.toString(),height = chain.size.height.toString())Log.d(TAG, logModel.toString())return chain.proceed(chain.request)}data class CoilLogModel(val url: String,val width: String,val height: String) {override fun toString(): String {return """URL: $urlwidth: $widthheight: $height""".trimIndent()}}
}
然后添加拦截器和自定义图像加载器
class MainApplication : Application(), ImageLoaderFactory {override fun newImageLoader(): ImageLoader {return ImageLoader.Builder(this.applicationContext).components {add(CoilLoggingInterceptor())}.build()}
}
示例结果如下:
创建一个自定义转换器
class GrayscaleTransformation() : Transformation {override val cacheKey: String = GrayscaleTransformation::class.java.nameoverride suspend fun transform(input: Bitmap, size: Size): Bitmap {val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)paint.colorFilter = COLOR_FILTERval output = createBitmap(input.width, input.height, input.config)output.applyCanvas {drawBitmap(input, 0f, 0f, paint)}return output}override fun equals(other: Any?) = other is GrayscaleTransformationoverride fun hashCode() = javaClass.hashCode()override fun toString() = "GrayscaleTransformation()"private companion object {val COLOR_FILTER = ColorMatrixColorFilter(ColorMatrix().apply { setSaturation(0f) })}
}
然后添加转换器到你的loader
// extension for image view
fun ImageView.loadGrayscaleImage(url: String) = this.load(url) {transformations(GrayscaleTransformation())
}// binding adapter for xml layout
@BindingAdapter("load_grayscale_image")
fun loadGrayscaleImage(view: ImageView, url: String) {view.loadGrayscaleImage(url)
}
有用的扩展函数和绑定适配器(Extensions and Binding Adapters)可用于Coil:
- 加载图像而不进行任何更改:
//binding adapter for xml layout
@BindingAdapter("load_image")
fun loadImage(view: ImageView, url: String) {view.load(url)
}
- 加载圆形图像
// extension for imageview
fun ImageView.loadCircularImage(url: String) = this.load(url) {transformations(CircleCropTransformation())
}// binding adapter for xml layouts
@BindingAdapter("load_circular_image")
fun loadCircularImage(view: ImageView, url: String) {view.loadCircularImage(url)
}
- 加载圆形边角图像
// extension for image view
fun ImageView.loadRoundedImage(url: String) = this.load(url) {transformations(RoundedCornersTransformation(30f, 30f, 30f, 30f))
}// binding adapter for xml layout
@BindingAdapter("load_rounded_image")
fun loadRoundedImage(view: ImageView, url: String) {view.loadRoundedImage(url)
}
- 加载模糊图像
// extension for image view
fun ImageView.loadBlurredImage(url: String) = this.load(url) {listener(onSuccess = { _, _ ->if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {setRenderEffect(RenderEffect.createBlurEffect(10f, 10f, Shader.TileMode.MIRROR))}})
}// binding adapter for xml layout
@BindingAdapter("load_blurred_image")
fun loadBlurredImage(view: ImageView, url: String) {view.loadBlurredImage(url)
}
Github
https://github.com/hakandindis/CoilAndroidExamples
https://coil-kt.github.io/coil
https://github.com/Commit451/coil-transformations