使用 Coil Compose 加载本地绘图

es0*_*329 4 android android-jetpack-compose coil jetpack-compose-accompanist

我最近从 Accompanist's 迁移ImagePainter到 Coil's,下面是我更新后的相关代码。

val painter = rememberImagePainter(DRAWABLE_RESOURCE_ID)

when (painter.state) {
    is ImagePainter.State.Empty -> Timber.w("Empty")
    is ImagePainter.State.Loading -> {
        Box(
            contentAlignment = Alignment.Center,
            modifier = Modifier.wrapContentSize()
        ) {
            CircularProgressIndicator()
        }
    }
    is ImagePainter.State.Success -> {
        Image(
            painter = painter,
            contentDescription = null,
            contentScale = ContentScale.Fit,
            modifier = Modifier
                .padding(8.dp)
                .size(84.dp)
                .clip(RoundedCornerShape(corner = CornerSize(16.dp)))
        )
    }
    is ImagePainter.State.Error -> Timber.e("Error")
}

Run Code Online (Sandbox Code Playgroud)

现在这些图像不会渲染并且painter.state始终为Empty。我的旧版 Accompanist 实现在代码中此时显示了图像。如果我使用 Compose 中的库存,它也可以工作painterResource(resId)

painter我在通过其状态执行 Coil 的 new 时缺少什么?

Ros*_*han 8

您可以使用可绘制对象的资源 ID 作为线圈 AsyncImage 可组合项的模型。

AsyncImage(
    model = R.drawable.bg_gradient,
    contentDescription = "Gradient background",
)
Run Code Online (Sandbox Code Playgroud)

Image可组合项 -和之间存在显着的性能差异AsyncImage。所以Coil的AsyncImage加载有时非常方便。