本文已参与「新人创作礼」活动,一起开启掘金创作之路。
SVG¶
要添加SVG支持, 需要引入扩展库:
implementation("io.coil-kt:coil-svg:2.2.0")
并且在构建ImageLoader
的时候在组件注册中添加解码器:
val imageLoader = ImageLoader.Builder(context)
.components {
add(SvgDecoder.Factory())
}
.build()
ImageLoader
将自动地探测并解码任何SVG文件. Coil通过在文件的前1KB中查找<svg
标记来探测SVG文件, 这应该能覆盖大多数场景. 如果SVG没能自动探测, 可以给该请求显式地设置Decoder
给SvgDecoder
.
Video Frame¶
要添加视频帧支持, 需要引入扩展库:
implementation("io.coil-kt:coil-video:2.2.0")
并且在构建ImageLoader
的时候在组件注册中添加解码器:
val imageLoader = ImageLoader.Builder(context)
.components {
add(VideoFrameDecoder.Factory())
}
.build()
如果想指定该帧的时间码从视频中解析, 需要使用videoFrameMillis
或者videoFrameMicros
:
imageView.load(File("/path/to/video.mp4")) {
videoFrameMillis(1000)
}
如果帧时间没有指定, 视频首帧将被解析.
ImageLoader
能够自动地探测任何视频并解析帧, 但前提是请求的文件名/URI以合法地视频扩展结尾. 如果没有的话, 需要给请求显式地设置Decoder
.
从Glide/Picasso中迁移¶
下面是一些例子展示了如何从Glide/Picasso调用迁移到Coil调用:
基础用法¶
// Glide
Glide.with(context)
.load(url)
.into(imageView)
// Picasso
Picasso.get()
.load(url)
.into(imageView)
// Coil
imageView.load(url)
自定义请求¶
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 (automatically detects the scale type)
imageView.load(url) {
placeholder(placeholder)
}
非View目标¶
// Glide (has optional callbacks for start and error)
Glide.with(context)
.load(url)
.into(object : CustomTarget<Drawable>() {
override fun onResourceReady(resource: Drawable, transition: Transition<Drawable>) {
// Handle the successful result.
}
override fun onLoadCleared(placeholder: Drawable) {
// Remove the drawable provided in onResourceReady from any Views and ensure no references to it remain.
}
})
// Picasso
Picasso.get()
.load(url)
.into(object : BitmapTarget {
override fun onBitmapLoaded(bitmap: Bitmap, from: Picasso.LoadedFrom) {
// Handle the successful result.
}
override fun onBitmapFailed(e: Exception, errorDrawable: Drawable?) {
// Handle the error drawable.
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {
// Handle the placeholder drawable.
}
})
// Coil
val request = ImageRequest.Builder(context)
.data(url)
.target(
onStart = { placeholder ->
// Handle the placeholder drawable.
},
onSuccess = { result ->
// Handle the successful result.
},
onError = { error ->
// Handle the error drawable.
}
)
.build()
context.imageLoader.enqueue(request)
后台线程¶
// Glide (blocks the current thread; must not be called from the main thread)
val drawable = Glide.with(context)
.load(url)
.submit(width, height)
.get()
// Picasso (blocks the current thread; must not be called from the main thread)
val drawable = Picasso.get()
.load(url)
.resize(width, height)
.get()
// Coil (suspends the current coroutine; non-blocking and thread safe)
val request = ImageRequest.Builder(context)
.data(url)
.size(width, height)
.build()
val drawable = context.imageLoader.execute(request).drawable