Android图片加载框架库源码解析 - Coil

文章目录
  • 一、什么是Coil

  • 二、引入Coil

      •   1、ImageView加载图片

            • 1.1、普通加载    

            • 1.2、crossfade(淡入淡出)加载

            • 1.3、crossfade的动画时间

            • 1.4、placeholder

1.5、error

1.6、高斯模糊

1.7、灰度变换

1.8、圆形

1.9、圆角

  2、Gif加载

  3、SVG加载(不存在)

           4、视频帧加载

    •   5、监听下载过程

    •   6、取消下载

    •   7、替换 okhttp 实例

    •   8、自定义

一、什么是Coil

Coil是一个Android开源的图片加载库,使用Kotlin协程来加载图片,Coil在 2020 年 10 月 22 日才发布了 1.0.0 版本,但却受到了 Android官方的推广,Coil有以下几个特点:

  • 更快:Coil在性能上做了很多优化,包括内存缓存和磁盘缓存、对内存中的图片进行采样、复用Bitmap、支持根据生命周期变化自动暂停和取消图片请求等

  • 更轻量级: Coil大约会给你的App增加两千个方法(前提是你的 App 已经集成了OkHttpCoroutines),Coil的方法数和Picasso相当,相比GlideFresco要轻量级很多

  • 更容易使用:Coil’s API 充分利用了Kotlin语言的新特性,简化并减少了很多重复代码

  • 更流行:Coil首选Kotlin语言开发,并且使用包含 CoroutinesOkHttpOkio 和 AndroidX Lifecycles 在内的更现代化的开源库

Coil的首字母由来:Coroutine,Image 和Loader 得到 Coil

Coil开源库github地址:https://github.com/coil-kt/coil

0e15f8c8a1e9c7bfc338d604fdf3c035.png

Coil官方文档:https://coil-kt.github.io/coil

4fa0268e3f8a3601b90aacf92f0946c3.png

二、引入Coil

Coil要求AndroidXJava 8+环境

app/build.gradle中添加Coil依赖包

implementation("io.coil-kt:coil:1.2.1")

AndroidManifest.xml中加上网络权限

<uses-permission android:name="android.permission.INTERNET" />

1、ImageView加载图片

activity_main.xml中声明ImageView,并使用CoilImageView加载图片:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp" />

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="点击" />
</LinearLayout>
1.1、普通加载
val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url)
        }
  • 通过扩展方法load加载url

  • 除了String以外,还支持HttpUrl 、Url、 File、 DrawableRes Int 、Drawable、 Bitmap等各种类型的加载

举例子:

// Resource
imageView.load(R.drawable.image)

// File
imageView.load(File("/path/to/image.jpg"))

08fbd2c8181ebb646e19087b684a3f0e.gif

1.2、crossfade(淡入淡出)加载
val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        reloadButton.setOnClickListener {
            imageView.load(url) {
                crossfade(true)
            }
        }

f01b537bfe334e49ac54be4e48fadd4b.gif

1.3、crossfade的动画时间
val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        reloadButton.setOnClickListener {
            imageView.load(url) {
                crossfade(3000)
            }
        }

e8a296f8bb23537102454fde3bbea04f.gif

1.4、placeholder

placeholder预置展位图

val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                placeholder(R.drawable.placeholder)
                crossfade(3000)
            }
        }

dfc51232a55cddb283ed98182fd85f55.gif

1.5、error

加载失败时的错误占位图片

val url = "https://notfound.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                error(R.drawable.error)
            }
        }

d47570f7a30754315cfacf49245b646c.gif

1.6、高斯模糊

BlurTransformation:高斯模糊变换
activity_main.xml代码中把ImageView的高度设置成300dp

val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                transformations(BlurTransformation(context = applicationContext, radius = 5f, sampling = 5f))
            }
        }

4e21b52515f6d5a7988267410af10fd0.gif

1.7、灰度变换

GrayscaleTransformation:灰度变换

val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                transformations(GrayscaleTransformation())
            }
        }

b06b45e66bed060e08ef684b203b8b4c.gif

1.8、圆形

CircleCropTransformation:圆形变换

val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                transformations(CircleCropTransformation())
            }
        }

9bf0daedba44ae5f348dc03c449168a5.gif

1.9、圆角

RoundedCornersTransformation:圆角矩形变换

val url = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(url) {
                transformations(
                    RoundedCornersTransformation(
                        topLeft = 10f,
                        topRight = 10f,
                        bottomLeft = 10f,
                        bottomRight = 10f
                    )
                )
            }
        }

a3ad890d0ddfe27ab601e69d889322bc.gif

上面左右可以设置圆角:topLeft = 10f,topRight = 10f,bottomLeft = 0f,bottomRight = 0f

4c8cc0ebced5e987a1bfefcf6500674c.png

下面左右可以设置圆角:topLeft = 0f,topRight = 0f,bottomLeft = 10f,bottomRight = 10f

7dc633c44fb53f81d15966fa91c5a8ef.png

2、Gif加载

添加依赖包:

implementation("io.coil-kt:coil-gif:1.4.0")

官方文档:https://coil-kt.github.io/coil/gifs/
创建 gif ImageLoader 实例

private val gifUrl = "https://img.zcool.cn/community/01ca905aebe350a801219b7f53a0e4.gif"
    ......
        button.setOnClickListener {

            val imageLoader = ImageLoader.Builder(this)
                .componentRegistry {
                    if (SDK_INT >= 28) {
                        add(ImageDecoderDecoder())
                    } else {
                        add(GifDecoder())
                    }
                }
                .build()

            //设置全局唯一实例
            Coil.setImageLoader(imageLoader)

            imageView.load(gifUrl) //加载gif图片
        }
    }

效果图如下:

bbbd00310a4fec5b15fed36ec2420bba.gif

3、SVG加载(不存在)

Coil也可以进行SVG加载的,同gif一样,也是需要添加extend包的:

implementation("io.coil-kt:coil-svg:1.2.2")//支持SVG

代码不存在了

4、视频帧加载

implementation("io.coil-kt:coil-video:1.2.2")//支持Video
private val videoUrl = "https://vd4.bdstatic.com/mda-jbppbefbbztvws50/sc/mda-jbppbefbbztvws50.mp4"
    ......
        button.setOnClickListener {

            //创建 gif ImageLoader 实例
            val imageLoader = ImageLoader.Builder(applicationContext)
                .componentRegistry {
                    add(VideoFrameDecoder(this@MainActivity))
                }.build()

            //设置全局唯一实例
            Coil.setImageLoader(imageLoader)

            imageView.load(videoUrl)
        }
    }

2d0208c7f9a15e131472e7fd539382e3.gif

5、监听下载过程

private val imageUrl = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            imageView.load(imageUrl) {
                listener(
                    onStart = { request ->
                        Log.d("coil-", "onStart")
                    },
                    onError = { request, throwable ->
                        Log.d("coil-", "onError")
                    },
                    onCancel = { request ->
                        Log.d("coil-", "onCancel")
                    },
                    onSuccess = { request, metadata ->
                        Log.d("coil-", "onSuccess")
                    }
                )
            }
        }

点击“点击”按钮后图片加载成功,可以看Logcat窗口中打印:

494462bb914704ce54a744fd0d6234e6.png

6、取消下载

private val imageUrl = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {
            val disposable = imageView.load(imageUrl)
            //取消加载
            disposable.dispose()
        }

7、替换 okhttp 实例

coil底层是使用okhttp作为网络请求工具,可以设置okHttpClient实例

private val imageUrl = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {

            val okHttpClient = OkHttpClient.Builder()
                .cache(CoilUtils.createDefaultCache(this))
                .build()

            val imageLoader = ImageLoader.Builder(this).okHttpClient {
                okHttpClient
            }.build()

            Coil.setImageLoader(imageLoader)

            imageView.load(imageUrl)
        }

81bd6780707f4d306a7a8fcb6339e27b.gif

8、自定义

private val imageUrl = "https://img-blog.csdnimg.cn/20210124002108308.png"
    ......
        button.setOnClickListener {

            val okHttpClient = OkHttpClient.Builder()
                .cache(CoilUtils.createDefaultCache(this))
                .build()

            val imageLoader = ImageLoader.Builder(this)
                .availableMemoryPercentage(0.2)
                .diskCachePolicy(CachePolicy.ENABLED) //磁盘缓策略 ENABLED、READ_ONLY、WRITE_ONLY、DISABLED
                .crossfade(true) //淡入淡出
                .crossfade(1000) //淡入淡出时间
                .okHttpClient { //设置okhttpClient实例
                    okHttpClient
                }.build()

            Coil.setImageLoader(imageLoader)
            imageView.load(imageUrl)

        }

35782054c50e6db5b8c2fe775bab4e6c.gif

博客链接:https://caobin.blog.youkuaiyun.com/article/details/134089606

借助 Android WebView API 提升对嵌入式媒体的信任

欢迎关注我的公众号

ba28f9a9e6f138c3b77a4a959ca9b775.png

长按上图,识别图中二维码即可关注

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值