AndroidJetpackCompose-图像无法缩放到框的宽度和高度
创建了 ImageCard 视图,用于在 android jetpack compose 中创建列表,但某些图像无法抓取到 Box 小部件的宽度和高度。
使用 640*427 图像并像图像 1 一样输出。
使用 6720*4480 图像,它看起来像图像 2。
使用下面的代码创建 ImageCard。
ImageCard 函数的用法:在 setContent{} 函数中调用 ImageCardData 函数
@Composable
fun ImageCard(
painter: Painter,
title: String,
contentDescription: String,
modifier: Modifier = Modifier
) {
Card(
modifier = modifier.fillMaxWidth(),
shape = RoundedCornerShape(10.dp),
elevation = 5.dp
) {
Box(
modifier = Modifier.height(200.dp)
) {
Image(
painter = painter,
contentDescription = contentDescription,
contentScale = ContentScale.Crop
)
Box(
modifier = Modifier
.fillMaxSize()
.background(
brush = Brush.verticalGradient(
colors = listOf(
Color.Transparent,
Color.Black
),
startY = 50f
)
)
)
Box(
modifier = Modifier
.fillMaxSize()
.padding(12.dp),
contentAlignment = Alignment.BottomStart
) {
Text(
text = title,
style = TextStyle(color = Color.White, fontSize = 16.sp)
)
}
}
}
}
@Composable
fun ImageCardData() {
val painter = painterResource(id = R.drawable.engagement)
val title = "Sample Text Title"
val description = "This is sample Image Description"
Box(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
) {
ImageCard(
painter = painter,
title = title,
contentDescription = description
)
}
}
回答
您的图像视图大小由它的内容计算,因为它没有任何大小修饰符。
添加fillMaxSize到图像:
Image(
painter = painter,
contentDescription = contentDescription,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)