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



我试图从图库中显示图像,如果用户选择任何内容,或者可绘制资源中的图像文件中的图像作为默认图像,这是不工作的。我正在使用Coil撰写和添加依赖已经。下面是代码:

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进行比较,这总是为真

你有两个选择:

  1. 根据状态值指定painter
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()
)
  1. 默认情况下,如果你传递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(
"https://i.stack.imgur.com/rkyep.jpg",
emptyPlaceholder = R.drawable.test,
),
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)

可以使用builder参数设置placeholder:

val painter = rememberImagePainter(
imageUriState.value,
builder = {
placeholder(R.drawable.blank_profile_picture)
}
)
Image(
painter,
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth()
)

从@Gabriele Mariotti的回答中找到了寻找漏洞的线索。我没有呼叫.value,而是呼叫imageUriState。修复了这个问题,现在它正在工作。谢谢大家的帮助!

Image(
painter = rememberImagePainter(
if (imageUriState.value != null) {
imageUriState.value
} else {
R.drawable.blank_profile_picture
}
),
contentDescription = "profile image",
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxWidth()
)

相关内容

  • 没有找到相关文章

最新更新