如何在 Jetpack Compose 画布上绘制图像,同时确保图像完全适合整个画布的宽度和高度,特别是当图像的分辨率明显大于画布尺寸时?我想减小图像的尺寸以匹配画布尺寸。
@Composable
fun Item(
imageResId: Int,
parallaxOffset: Float,
pagerHeight: Dp,
screenWidth: Dp,
density: Float,
scaleFactor: Float,
modifier: Modifier = Modifier,
imageCornerRadius: Dp = 24.dp,
imageHeight: Dp = 250.dp,
) {
// Load the image bitmap
val imageBitmap = ImageBitmap.imageResource(id = imageResId)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
// Card composable for the item
Box(modifier = modifier
.graphicsLayer {
scaleX = scaleFactor
scaleY = scaleFactor
}
.clip(RoundedCornerShape(imageCornerRadius))) {
Canvas(
modifier = Modifier
.fillMaxWidth()
.height(250.dp)
.clip(shape)
) {)
translate(left = parallaxOffset * density) {
// Draw the image
drawImage(
image = imageBitmap,
dstOffset = IntOffset(-xOffset.toIntPx(density), 0),
)
}
}
}
}
}
如果需要,您可以使用
dstSize
参数来绘制整个画布。
srcSize
图像本身应该画多大
dstSize
画布内的绘制区域应该有多大
默认情况下,
dstSize
等于srcSize
,因此当图像较小时,绘制区域小于画布。当 srcSize 大于 Canvas dstSize 时,它会将其绘制为与图像像素一样大,但由于我们只能看到屏幕,因此当图像很大时,您只能看到屏幕的一部分。通过更改 srcOffset,您也可以设置在这种情况下绘制哪个部分。
您可以在本教程中测试 srcSize/Offset、dstSize/Offset 参数,以及您可以添加到其中的任何图像。
结果来自比 Canvas 大的图像。第一个绘制剖面,而第二个图像适合画布。
@Preview
@Composable
private fun CanvasScaleTest() {
val imageBitmap = ImageBitmap.imageResource(R.drawable.sample)
Column {
Canvas(
modifier = Modifier.fillMaxWidth().aspectRatio(4/3f).clipToBounds()
) {
drawImage(
image = imageBitmap,
)
}
Spacer(modifier = Modifier.height(20.dp))
Canvas(
modifier = Modifier.fillMaxWidth().aspectRatio(4/3f).clipToBounds()
) {
val canvasWidth = size.width.toInt()
val canvasHeight = size.height.toInt()
drawImage(
image = imageBitmap,
dstSize = IntSize(canvasWidth, canvasHeight)
)
}
}
}