【问题标题】:How to modify color and size for Coil image placeholder in Jetpack Compose如何在 Jetpack Compose 中修改线圈图像占位符的颜色和大小
【发布时间】:2021-11-24 20:05:51
【问题描述】:

我在 Jetpack Compose 中使用 Coil 1.3.2,我有一个像这样的 Image

Image(
    painter = rememberImagePainter(
        data = imageUrl,
        onExecute = { _, _ -> true },
        builder = {
            placeholder(R.drawable.icon)
        }
    ),
    contentScale = ContentScale.FillWidth,
    contentDescription = null,
    modifier = Modifier
        .fillMaxWidth()
        .aspectRatio(1f)
)

如何为占位符图标设置自定义颜色和大小?
我在documentation 上没有找到任何示例

【问题讨论】:

    标签: android android-jetpack-compose android-image android-icons coil


    【解决方案1】:

    您可以使用painter.state 查看图像是否仍在加载,并使用Box 显示所需的占位符。注意要加载的Image必须在视图层次结构中,仅仅定义rememberImagePainter不会开始加载。

    您可以使用ImageIcon 作为占位符:如果您需要更改色调颜色,第二个选项看起来更简洁:

    Box(contentAlignment = Alignment.Center) {
        val painter = rememberImagePainter(data = imageUrl)
        Image(
            painter = painter,
            contentScale = ContentScale.FillWidth,
            contentDescription = null,
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(1f)
        )
        if (painter.state !is ImagePainter.State.Success) {
            Icon(
                painter = painterResource(id = R.drawable.icon),
                contentDescription = null,
                tint = Color.Blue,
                modifier = Modifier.size(100.dp)
            )
        }
    }
    

    我使用contentAlignment = Alignment.CenterBox 中的静态大小占位符居中,您也可以将Modifier.matchParentSize() 添加到占位符,使其与图像大小相同,使用fillMaxSize(part) 取@ 987654333@父空间等

    您也可以使用AnimatedVisibility 代替if 添加动画。

    【讨论】:

      【解决方案2】:

      AFAIK 你不能直接使用资源来做到这一点,但你可以使用不同的placeholder 重载来获取Drawable 对象。您可以尝试直接在该对象中执行您需要的操作

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-05
        • 2022-12-16
        • 1970-01-01
        • 1970-01-01
        • 2022-08-09
        • 2022-11-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多