本文转载自微信公众号「Android开发编程」,作者Android开发编程。转载本文请联系Android开发编程公众号。
前言
Coil是Android上的一个全新的图片加载框架,它的全名叫做coroutine image loader,即协程图片加载库;
与传统的图片加载库Glide,Picasso或Fresco等相比。该具有轻量(只有大约1500个方法)、快、易于使用、更现代的API等优势;
它支持GIF和SVG,并且可以执行四个默认转换:模糊,圆形裁剪,灰度和圆角。并且是全用Kotlin编写,如果你是纯Kotlin项目的话,那么这个库应该是你的首选;
一、Coil介绍和使用
1、Coil介绍
Coil 是一个 Android 图片加载库,通过 Kotlin 协程的方式加载图片。特点如下:
- 更快: Coil 在性能上有很多优化,包括内存缓存和磁盘缓存,把缩略图存保存在内存中,循环利用 bitmap,自动暂停和取消图片网络请求等;
- 更轻量级:Coil 只有2000个方法(前提是你的 APP 里面集成了 OkHttp 和 Coroutines),Coil 和 Picasso 的方法数差不多,相比 Glide 和 Fresco 要轻量很多;
- 更容易使用: Coil 的 API 充分利用了 Kotlin 语言的新特性,简化和减少了很多样板代码;
- 更流行: Coil 首选 Kotlin 语言开发并且使用包含 Coroutines, OkHttp, Okio 和 AndroidX Lifecycles 在内最流行的开源库;
2、使用
①Coil 可以在 mavenCentral() 下载
implementation("io.coil-kt:coil:1.2.1")
- 1.
②可以使用 ImageView 的扩展函数 load 加载一张图片:
// URL
imageView.load("https://www.example.com/image.jpg")
// Resource
imageView.load(R.drawable.image)
// File
imageView.load(File("/path/to/image.jpg"))
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
可以使用 lambda 语法轻松配置请求选项:
imageView.load("https://www.example.com/image.jpg") {
crossfade(true)
placeholder(R.drawable.image)
transformations(CircleCropTransformation())
}
- 1.
- 2.
- 3.
- 4.
- 5.
error
imageView.load(url) {
error(R.drawable.error)
}
- 1.
- 2.
- 3.
placeholder预置展位图
imageView.load(url) {
placeholder(R.drawable.placeholder)
crossfade(3000)
}
- 1.
- 2.
- 3.
- 4.
crossfade的动画时间
imageView.load(url) {
crossfade(3000)
}
- 1.
- 2.
- 3.
③transformations
Coil默认提供了四种变换:模糊变换(BlurTransformation)、圆形变换(CircleCropTransformation)、灰度变换(GrayscaleTransformation)和圆角变换(RoundedCornersTransformation)
基础用法:
imageView.load(IMAGE_URL){
transformations(GrayscaleTransformation())
}
- 1.
- 2.
- 3.
直接加入变换就可以, 同时可支持多种变换:
imageView.load(IMAGE_URL) {
transformations(GrayscaleTransformation(),
RoundedCornersTransformation(topLeft = 2f, topRight =
2f,bottomLeft = 40f, bottomRight = 40f))
}
- 1.
- 2.
- 3.
- 4.
- 5.
④Gif加载
Coil基础包中是不支持Gif加载的,需要添加extend包:
implementation("io.coil-kt:coil-gif:0.9.5")
- 1.
此时需要更改一下代码的方式,在imageLoader中注册Gif组件:
val gifImageLoader = ImageLoader(this) {
componentRegistry {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
add(ImageDecoderDecoder())
} else {
add(GifDecoder())
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
使用本组件之后,ImageView可直接使用:
id_image_gif.load(GIF_IMAGE_URL, gifImageLoader)
- 1.
⑤SVG加载
Coil也可以进行SVG加载的,同gif一样,也是需要添加extend包的:
implementation("io.coil-kt:coil-svg:0.9.5")
- 1.
代码如下:
val svgImageLoader = ImageLoader(this){
componentRegistry {
add(SvgDecoder(this@MainActivity))
}
}
id_image_svg.load(R.drawable.ic_directions_bus_black_24dp, svgImageLoader)
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
总结
Coil可以配合Kotlin协程实现图片加载:
- 加载性能好:缓存管理(MemCache、DiskCache)、动态采样(Dynamic image sampling)、加载中暂停/终止等功能有助于提高图片加载效率
- 体积小:其包体积与Picasso相当,显著低于Glide和Fresco,仅仅只有1500个方法,但是在功能上却不输于其他同类库;
- 简单易用:配合Kotlin扩展方法等语法优势,API简单易用;
- 技术先进:基于Coroutine、OkHttp、Okio、AndroidX等先端技术开发,确保了技术上的先进性;