Kamel 是一个为 Compose Multiplatform 设计的异步媒体加载库。它提供了一种简单、可定制且高效的方式来加载、缓存、解码和显示应用程序中的图像。默认情况下,它使用 Ktor 客户端加载资源。
Kamel 已发布在 Maven Central 上:
repositories { mavenCentral() // ... }
将依赖项添加到公共源集:
kotlin { sourceSets { commonMain { dependencies { implementation("media.kamel:kamel-image:0.9.5") // ... } } } }
将依赖项添加到依赖项块:
dependencies { implementation("media.kamel:kamel-image:0.9.5") // ... }
请确保为您的平台添加 Ktor HttpClient 引擎的依赖项,使用这个链接。
要异步加载图像,您可以使用 asyncPainterResource 可组合函数,它可以从不同的数据源加载图像:
// 字符串 asyncPainterResource(data = "https://www.example.com/image.jpg") // Ktor Url asyncPainterResource(data = Url("https://www.example.com/image.jpg")) // URI asyncPainterResource(data = URI("https://www.example.com/image.png")) // 文件(JVM,Native) asyncPainterResource(data = File("/path/to/image.png")) // 文件(JS) asyncPainterResource(data = File(org.w3c.files.File(arrayOf(blob), "/path/to/image.png"))) // URL asyncPainterResource(data = URL("https://www.example.com/image.jpg")) // 以及更多...
asyncPainterResource 可用于加载 SVG、XML、JPEG 和 PNG 格式的图像,具体取决于平台实现。
asyncPainterResource 返回一个 Resource<Painter> 对象,可以使用 KamelImage 可组合函数来显示图像。
由于 Android 和桌面之间没有共享的资源系统,某些实现(例如获取器和映射器)仅适用于特定平台:
要从桌面应用程序资源加载图像文件,您必须将 resourcesFetcher 添加到 KamelConfig 中:
val desktopConfig = KamelConfig { takeFrom(KamelConfig.Default) // 仅在桌面上可用 resourcesFetcher() // 仅在桌面上可用 // 一个替代的 svg 解码器 batikSvgDecoder() }
假设项目的 /resources 目录中有一个 image.png 文件:
CompositionLocalProvider(LocalKamelConfig provides desktopConfig) { asyncPainterResource("image.png") }
要从 Android 应用程序资源加载图像文件,您必须将 resourcesFetcher 和 resourcesIdMapper 添加到 KamelConfig 中:
val context: Context = LocalContext.current val androidConfig = KamelConfig { takeFrom(KamelConfig.Default) // 仅在 Android 上可用 resourcesFetcher(context) // 仅在 Android 上可用 resourcesIdMapper(context) }
假设项目的 /res/raw 目录中有一个 image.png 文件:
CompositionLocalProvider(LocalKamelConfig provides androidConfig) { asyncPainterResource(R.raw.image) }
asyncPainterResource 支持使用尾随 lambda 进行配置:
val painterResource: Resource<Painter> = asyncPainterResource("https://www.example.com/image.jpg") { // 加载图像时使用的 CoroutineContext coroutineContext = Job() + Dispatcher.IO // 自定义 HTTP 请求 requestBuilder { // this: HttpRequestBuilder header("Key", "Value") parameter("Key", "Value") cacheControl(CacheControl.MAX_AGE) } }
KamelImage 是一个可组合函数,它接受一个 Resource<Painter> 对象,显示它并提供额外的功能:
KamelImage( resource = painterResource, contentDescription = "Profile", )
KamelImage 还可以用于通过 onFailure 获取 exception,
并使用 onLoading 参数的 progress,根据情况显示 snackbar 或进度指示器:
val coroutineScope = rememberCoroutineScope() val snackbarHostState = remember { SnackbarHostState() } Box { KamelImage( resource = painterResource, contentDescription = "个人资料", onLoading = { progress -> CircularProgressIndicator(progress) }, onFailure = { exception -> coroutineScope.launch { snackbarHostState.showSnackbar( message = exception.message.toString(), actionLabel = "隐藏", duration = SnackbarDuration.Short ) } } ) SnackbarHost(hostState = snackbarHostState, modifier = Modifier.padding(16.dp)) }
你也可以使用简单的 when 表达式提供自己的自定义实现:
when (val resource = asyncPainterResource("https://www.example.com/image.jpg")) { is Resource.Loading -> { Text("加载中...") } is Resource.Success -> { val painter: Painter = resource.value Image(painter, contentDescription = "个人资料") } is Resource.Failure -> { log(resource.exception) val fallbackPainter = painterResource("/path/to/fallbackImage.jpg") Image(fallbackPainter, contentDescription = "个人资料") } }
你可以通过 animationSpec 参数启用、禁用或自定义交叉淡入淡出(渐入)动画。将 animationSpec 设置为 null 将禁用动画:
KamelImage( resource = imageResource, contentDescription = "个人资料", // 默认为 null animationSpec = tween(), )
默认实现是 KamelConfig.Default。如果你希望配置它,可以按以下方式进行:
val customKamelConfig = KamelConfig { // 如果需要,复制默认实现 takeFrom(KamelConfig.Default) // 设置要缓存的图像数量 imageBitmapCacheSize = DefaultCacheSize // 添加 ImageBitmapDecoder imageBitmapDecoder() // 添加 ImageVectorDecoder (XML) imageVectorDecoder() // 添加 SvgDecoder (SVG) svgDecoder() // 添加 FileFetcher fileFetcher() // 配置 Ktor HttpClient httpFetcher { // httpCache 在 kamel-core 中定义,配置 ktor 客户端 // 安装 HttpCache 功能,使用 Kamel 提供的实现。 // 可以以字节为单位定义缓存大小。 httpCache(10 * 1024 * 1024 /* 10 MiB */) defaultRequest { url("https://www.example.com/") cacheControl(CacheControl.MaxAge(maxAgeSeconds = 10000)) } install(HttpRequestRetry) { maxRetries = 3 retryIf { httpRequest, httpResponse -> !httpResponse.status.isSuccess() } } // 需要添加 "io.ktor:ktor-client-logging:$ktor_version" Logging { level = LogLevel.INFO logger = Logger.SIMPLE } } // 更多可用功能。 }
Kamel 提供了一个通用的 Cache<K,V> 接口,默认实现使用基于 LinkedHashMap 的 LRU 内存缓存机制。你可以为每种类型提供要缓存的条目数,如下所示:
KamelConfig { // 默认为 100 imageBitmapCacheSize = 500 // 默认为 100 imageVectorCacheSize = 300 // 默认为 100 svgCacheSize = 200 }
Kamel 可以通过 实现 ktor 的 CacheStorage 功能为图像创建持久磁盘缓存。默认配置 KamelConfig.Default 安装此功能,磁盘缓存大小为 10 MiB。底层磁盘缓存基于 coil 的多平台 DiskLruCache 实现。
KamelConfig { httpFetcher { // 缓存大小可以以字节为单位定义。或者可以使用 DefaultHttpCacheSize(10 MiB)。 httpCache(DefaultHttpCacheSize) } }
你可以使用 LocalKamelConfig 应用自定义配置:
CompositionLocalProvider(LocalKamelConfig provides customKamelConfig) { asyncPainterResource("image.jpg") }
欢迎随时贡献!如果你想贡献,请随时创建 PR 或开启 issue。
Copyright 2021 Ali Albaali
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.