mcpField
C
coil-compose

coil-compose

github.com/new-silvermoon开发992444 次安装13 周前更新
代码仓库

关于 coil-compose

此技能介绍如何在 Jetpack Compose 中使用 Coil 加载图片,帮助 Android 开发者选择合适的可组合项,并处理加载状态、尺寸、无障碍和性能。

主要功能

  1. 01AsyncImage 使用指导
  2. 02Painter 与插槽 API 选择
  3. 03加载及错误状态处理
  4. 04图片尺寸与变换
  5. 05缓存和无障碍实践

适用场景

  1. 01在 Compose 中显示远程图片
  2. 02自定义加载和错误界面
  3. 03在 Canvas 或 Icon 中加载图片
  4. 04调整列表中的图片请求

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/new-silvermoon/awesome-android-agent-skills --skill coil-compose

安装后在 Claude Code 中输入/coil-compose确认已加载。

详细介绍

Jetpack Compose 的 Coil

说明

在 Jetpack Compose 中实现图片加载时,请使用 Coil(Coroutines Image Loader)。由于其高效且与 Compose 无缝集成,它是 Compose 的推荐库。

1. 主要可组合项:AsyncImage

大多数情况下请使用 AsyncImage。它会自动处理尺寸解析,并支持标准 Image 参数。

AsyncImage(
    model = ImageRequest.Builder(LocalContext.current)
        .data("https://example.com/image.jpg")
        .crossfade(true)
        .build(),
    placeholder = painterResource(R.drawable.placeholder),
    error = painterResource(R.drawable.error),
    contentDescription = stringResource(R.string.description),
    contentScale = ContentScale.Crop,
    modifier = Modifier.clip(CircleShape)
)
2. 底层控制:rememberAsyncImagePainter

仅当你需要 Painter 而非可组合项(例如用于 Canvas 或 Icon),或需要手动观察加载状态时,才使用 rememberAsyncImagePainter。

警告

rememberAsyncImagePainter 无法检测图片在屏幕上的加载尺寸,默认始终按图片的原始尺寸加载。除非确实需要 Painter,否则请使用 AsyncImage。

val painter = rememberAsyncImagePainter(
    model = ImageRequest.Builder(LocalContext.current)
        .data("https://example.com/image.jpg")
        .size(Size.ORIGINAL) // Explicitly define size if needed
        .build()
)
3. 插槽 API:SubcomposeAsyncImage

当你需要为不同状态(加载、成功、错误)自定义插槽 API 时,请使用 SubcomposeAsyncImage。

注意

子组合比常规组合更慢。避免在 LazyColumn 或 LazyRow 等对性能要求较高的区域使用 SubcomposeAsyncImage。

SubcomposeAsyncImage(
    model = "https://example.com/image.jpg",
    contentDescription = null,
    loading = {
        CircularProgressIndicator()
    },
    error = {
        Icon(Icons.Default.Error, contentDescription = null)
    }
)
4. 性能与最佳实践
  • 单例 ImageLoader:整个应用使用同一个 ImageLoader 实例,以共享磁盘/内存缓存。
  • 主线程安全:Coil 会自动在后台线程上执行图片请求。
  • 交叉淡入淡出:始终在 ImageRequest 中启用 crossfade(true),让占位图到加载成功状态的过渡更平滑。
  • 尺寸:确保正确设置 contentScale,避免加载不必要的大图。
5. 实现检查清单
  • 优先使用 AsyncImage,而非其他变体。
  • 始终提供有意义的 contentDescription,或将其设为 null,用于装饰性图片。
  • 使用 crossfade(true) 改善用户体验。
  • 避免在列表中使用 SubcomposeAsyncImage。
  • 根据具体需求配置 ImageRequest,例如设置变换(如 CircleCropTransformation)。

评论

支持 Markdown