框架介绍
Coil是Android上的一个全新的图片加载框架,它的全名叫做coroutine image loader,即协程图片加载库。与传统的图片加载库Glide,Picasso或Fresco等相比。该具有轻量(只有大约1500个方法)、快、易于使用、更现代的API等优势。它支持GIF和SVG,并且可以执行四个默认转换:模糊,圆形裁剪,灰度和圆角。并且是全用Kotlin编写,如果你是纯Kotlin项目的话,那么这个库应该是你的首选。
这应该是一个很新的一个图片加载库,完全使用kotlin编写,使用了kotlin的协程,图片网络请求方式默认为Okhttp,相比较于我们常用的Picasso,Glide或者Fresco,它有以下几个特点:
- 足够快速,它在内存、图片存储、图片的采样、Bitmap重用、暂停\取消下载等细节方面都有很大的优化(相比于上面讲的三大框架);
- 足够轻量,只有大概1500个核心方法,当然也是相对于PGF而言的;
- 足够新,也足够现代!使用了最新的Koltin协程所编写,充分发挥了CPU的性能,同时也使用了OKHttp、Okio、LifeCycle等比较新式的Android库。
使用
github地址为:https://github.com/coil-kt/coil/
首先需要配置你的AS环境包含Kotlin开发环境,然后添加依赖:
implementation("io.coil-kt:coil:1.1.1")
要将图像加载到ImageView中,请使用加载扩展功能:
1// URL 2imageView.load("https://www.example.com/image.jpg") 3 4// Resource 5imageView.load(R.drawable.image) 6 7// File 8imageView.load(File("/path/to/image.jpg")) 9 10// And more...
可以使用可选的配置请求:
1imageView.load("https://www.example.com/image.jpg") { 2 crossfade(true) 3 placeholder(R.drawable.image) 4 transformations(CircleCropTransformation()) 5}
基本变化:
Coil默认提供了四种变换:模糊变换(BlurTransformation)、圆形变换(CircleCropTransformation)、灰度变换(GrayscaleTransformation)和圆角变换(RoundedCornersTransformation):
基础用法:
1imageView.load(IMAGE_URL){ 2 transformations(GrayscaleTransformation()) 3}
直接加入变换就可以, 同时可支持多种变换:
1 imageView.load(IMAGE_URL) { 2 transformations(GrayscaleTransformation(), 3 RoundedCornersTransformation(topLeft = 2f, topRight = 4 2f,bottomLeft = 40f, bottomRight = 40f)) 5}
Gif加载
Coil基础包中是不支持Gif加载的,需要添加extend包:
implementation("io.coil-kt:coil-gif:0.9.5")
此时需要更改一下代码的方式,在imageLoader中注册Gif组件:
1val gifImageLoader = ImageLoader(this) { 2 componentRegistry { 3 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { 4 add(ImageDecoderDecoder()) 5 } else { 6 add(GifDecoder()) 7 } 8 } 9}
使用本组件之后,ImageView可直接使用:
id_image_gif.load(GIF_IMAGE_URL, gifImageLoader)
SVG加载
Coil也可以进行SVG加载的,同gif一样,也是需要添加extend包的:
implementation("io.coil-kt:coil-svg:0.9.5")
代码如下:
1val svgImageLoader = ImageLoader(this){ 2 componentRegistry { 3 add(SvgDecoder(this@MainActivity)) 4 } 5 } 6 7id_image_svg.load(R.drawable.ic_directions_bus_black_24dp, svgImageLoader)
从Glide\Picasso迁移到Coil
基本的用法的扩展为:
1// Glide 2 Glide.with(context) 3 .load(url) 4 .into(imageView) 5 6// Picasso 7 Picasso.get() 8 .load(url) 9 .into(imageView) 10 11// Coil 12 imageView.load(url)
图片设置ScaleType的方式:
1imageView.scaleType = ImageView.ScaleType.FIT_CENTER 2 3 // Glide 4 Glide.with(context) 5 .load(url) 6 .placeholder(placeholder) 7 .fitCenter() 8 .into(imageView) 9 10 // Picasso 11 Picasso.get() 12 .load(url) 13 .placeholder(placeholder) 14 .fit() 15 .into(imageView) 16 17 // Coil (autodetects the scale type) 18 imageView.load(url) { 19 placeholder(placeholder) 20}
