gpt4 book ai didi

android - 使用 Coil 和 Jetpack Compose 有条件地显示图库或可绘制资源中的图像

转载 作者:行者123 更新时间:2023-12-05 00:15:10 25 4
gpt4 key购买 nike

我试图显示图库中的图像(如果用户选择了任何内容),或者显示可绘制资源中图像文件中的图像作为默认图像,但这是不起作用的。我正在使用 Coil 进行 Compose 并添加了依赖项。这是代码:

class MainActivity : ComponentActivity() {
private var imageUriState = mutableStateOf<Uri?>(null)

private val selectImageLauncher = registerForActivityResult(GetContent()) { uri ->
imageUriState.value = uri
}

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ImageSourceActivityScreen()
}
}

@Composable
fun ImageSourceActivityScreen() {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
Image(
painter = rememberImagePainter(
if (imageUriState != null) {
imageUriState.value
} else {
R.drawable.blank_profile_picture
}
),
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth()
)
...
}

没有显示错误,但默认图像也没有显示。请帮助使其发挥作用。谢谢!

最佳答案

您的代码不起作用,因为您将 imageUriStatenull 进行比较,而 null 始终为 true

您有两个选择:

  1. 根据您的状态值指定画家
Image(
painter = if (imageUriState.value != null) {
rememberImagePainter(
imageUriState.value
)
} else {
painterResource(id = R.drawable.blank_profile_picture)
},
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth()
)
  • 默认情况下,如果您将 null 作为数据传递,线圈不会显示占位符,这通常是有意义的。如果您想在没有图像时和等待图像加载时看到占位符,您可以创建这样的函数:
  • @Composable
    inline fun rememberImagePainter(
    data: Any?,
    @DrawableRes emptyPlaceholder: Int,
    builder: ImageRequest.Builder.() -> Unit = {},
    ): Painter {
    val painter = rememberImagePainter(
    data,
    builder = {
    placeholder(emptyPlaceholder)
    builder()
    }
    )
    if (data == null) {
    return painterResource(emptyPlaceholder)
    }
    return painter
    }

    // usage
    Image(
    painter = rememberImagePainter(
    "/image/rkyep.jpg",
    emptyPlaceholder = R.drawable.test,
    ),
    contentDescription = "profile image",
    contentScale = ContentScale.Crop,
    modifier = Modifier.fillMaxSize()
    )

    关于android - 使用 Coil 和 Jetpack Compose 有条件地显示图库或可绘制资源中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68713558/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com