我有这个可组合项,我希望图像占据所有水平空间并调整垂直大小,以免剪切或更改图像的形状。 我没有找到任何方法来实现此目的,因此我必须为框设置固定高度并使用 ContentScale.Crop。
我尝试使用 Intrinsic 修饰符,但没有结果,它不能像用于 XML 布局的 wrap_content 一样工作。
这是我想要实现的用户界面,但我希望高度不固定。
private fun DrawCoverForPhone(cover: Cover?) {
val context = LocalContext.current
val painter = rememberAsyncImagePainter(
ImageRequest.Builder(context)
.data(data = cover?.large)
.crossfade(true)
.error(context.logoMarkPlaceholder())
.build()
)
Box(
modifier = Modifier
.height(140.dp)
.background(Colors.neutral50)
.clip(
RoundedCornerShape(
topEnd = 8.dp,
topStart = 8.dp,
bottomStart = 0.dp,
bottomEnd = 0.dp
)
)
) {
if (painter.state is AsyncImagePainter.State.Error) {
Image(
modifier = Modifier
.padding(vertical = Theme.dimensions.spacingMedium)
.fillMaxWidth()
.fillMaxHeight(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Fit
)
} else {
Image(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop
)
}
}
你可以尝试:
private fun DrawCoverForPhone(cover: Cover?) {
val context = LocalContext.current
val painter = rememberAsyncImagePainter(
ImageRequest.Builder(context)
.data(data = cover?.large)
.crossfade(true)
.error(context.logoMarkPlaceholder())
.build()
)
Box(
modifier = Modifier
.background(Colors.neutral50)
.clip(
RoundedCornerShape(
topEnd = 8.dp,
topStart = 8.dp,
bottomStart = 0.dp,
bottomEnd = 0.dp
)
)
) {
if (painter.state is AsyncImagePainter.State.Error) {
Image(
modifier = Modifier
.padding(vertical = Theme.dimensions.spacingMedium)
.fillMaxWidth()
.fillMaxHeight(),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Fit
)
} else if (painter.state is AsyncImagePainter.State.Success) {
val ratioModifier = painter.state.painter.intrinsicSize.let { intrinsicSize ->
Modifier.aspectRatio(intrinsicSize.width / intrinsicSize.height)
}
Image(
modifier = Modifier
.fillMaxWidth()
.then(ratioModifier),
painter = painter,
contentDescription = null,
contentScale = ContentScale.Crop
)
}
}
说明:
首先,从
.height(140.dp)
中删除 Box
,以便它将占据其子级的大小,然后,将 .fillMaxHeight()
替换为 .then(ratioModifier)
,其中 .aspectRatio(ratio)
应用于 Image
。
重要:
在这里,您需要根据加载图像的尺寸计算
ratio
,以便Image
尽可能宽,并且不会剪切/裁剪实际图像。
示例:
val width = 200F
val height = 100F
val ratio = width / height
希望这有效。