框架介紹
Coil是Android上的一個(gè)全新的圖片加載框架,它的全名叫做coroutine image loader,即協(xié)程圖片加載庫趾盐。與傳統(tǒng)的圖片加載庫Glide,Picasso或Fresco等相比屎开。該具有輕量(只有大約1500個(gè)方法)谦屑、快、易于使用涛漂、更現(xiàn)代的API等優(yōu)勢赏表。它支持GIF和SVG,并且可以執(zhí)行四個(gè)默認(rèn)轉(zhuǎn)換:模糊匈仗,圓形裁剪瓢剿,灰度和圓角。并且是全用Kotlin編寫悠轩,如果你是純Kotlin項(xiàng)目的話间狂,那么這個(gè)庫應(yīng)該是你的首選。
這應(yīng)該是一個(gè)很新的一個(gè)圖片加載庫火架,完全使用kotlin編寫鉴象,使用了kotlin的協(xié)程忙菠,圖片網(wǎng)絡(luò)請求方式默認(rèn)為Okhttp,相比較于我們常用的Picasso,Glide或者Fresco纺弊,它有以下幾個(gè)特點(diǎn):
- 足夠快速牛欢,它在內(nèi)存、圖片存儲淆游、圖片的采樣傍睹、Bitmap重用、暫停\取消下載等細(xì)節(jié)方面都有很大的優(yōu)化(相比于上面講的三大框架)犹菱;
- 足夠輕量焰望,只有大概1500個(gè)核心方法,當(dāng)然也是相對于PGF而言的已亥;
- 足夠新熊赖,也足夠現(xiàn)代!使用了最新的Koltin協(xié)程所編寫虑椎,充分發(fā)揮了CPU的性能震鹉,同時(shí)也使用了OKHttp、Okio捆姜、LifeCycle等比較新式的Android庫传趾。
使用
github地址為:https://github.com/coil-kt/coil/
首先需要配置你的AS環(huán)境包含Kotlin開發(fā)環(huán)境,然后添加依賴:
implementation("io.coil-kt:coil:1.1.1") 要將圖像加載到ImageView中泥技,請使用加載擴(kuò)展功能:
// URL
imageView.load("https://www.example.com/image.jpg")
// Resource
imageView.load(R.drawable.image)
// File
imageView.load(File("/path/to/image.jpg"))
// And more...
可以使用可選的配置請求:
imageView.load("https://www.example.com/image.jpg") {
crossfade(true)
placeholder(R.drawable.image)
transformations(CircleCropTransformation())
}
基本變化:
Coil默認(rèn)提供了四種變換:模糊變換(BlurTransformation)浆兰、圓形變換(CircleCropTransformation)、灰度變換(GrayscaleTransformation)和圓角變換(RoundedCornersTransformation):
基礎(chǔ)用法:
imageView.load(IMAGE_URL){
transformations(GrayscaleTransformation())
}
直接加入變換就可以, 同時(shí)可支持多種變換:
imageView.load(IMAGE_URL) {
transformations(GrayscaleTransformation(),
RoundedCornersTransformation(topLeft = 2f, topRight =
2f,bottomLeft = 40f, bottomRight = 40f))
}
Gif加載
Coil基礎(chǔ)包中是不支持Gif加載的珊豹,需要添加extend包:
implementation("io.coil-kt:coil-gif:0.9.5")
此時(shí)需要更改一下代碼的方式簸呈,在imageLoader中注冊Gif組件:
val gifImageLoader = ImageLoader(this) {
componentRegistry {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
add(ImageDecoderDecoder())
} else {
add(GifDecoder())
}
}
}
使用本組件之后,ImageView可直接使用:
id_image_gif.load(GIF_IMAGE_URL, gifImageLoader)
SVG加載
Coil也可以進(jìn)行SVG加載的店茶,同gif一樣蜕便,也是需要添加extend包的:
implementation("io.coil-kt:coil-svg:0.9.5")
代碼如下:
val svgImageLoader = ImageLoader(this){
componentRegistry {
add(SvgDecoder(this@MainActivity))
}
}
id_image_svg.load(R.drawable.ic_directions_bus_black_24dp, svgImageLoader)
從Glide\Picasso遷移到Coil
基本的用法的擴(kuò)展為:
// Glide
Glide.with(context)
.load(url)
.into(imageView)
// Picasso
Picasso.get()
.load(url)
.into(imageView)
// Coil
imageView.load(url)
圖片設(shè)置ScaleType的方式:
imageView.scaleType = ImageView.ScaleType.FIT_CENTER
// Glide
Glide.with(context)
.load(url)
.placeholder(placeholder)
.fitCenter()
.into(imageView)
// Picasso
Picasso.get()
.load(url)
.placeholder(placeholder)
.fit()
.into(imageView)
// Coil (autodetects the scale type)
imageView.load(url) {
placeholder(placeholder)
}