在 Jetpack Compose 中剪辑图像

Bas*_*rif 3 android android-jetpack-compose android-compose-image

我正在使用 Clip 来使用 Compose 修剪图像,以仅显示图像的左边缘部分。但它保持了带有空白的宽度。如何裁剪正确的部分(标记为红色)?

在此输入图像描述

我尝试为图像设置自定义宽度,但它没有按预期工作。

在此输入图像描述

这是我正在使用的代码,

object CropShape : Shape {
    override fun createOutline(
        size: androidx.compose.ui.geometry.Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline = Outline.Rectangle(
        Rect(Offset.Zero, androidx.compose.ui.geometry.Size((58 * density.density), size.height))
    )
}

@Composable
private fun test(){

Image(
        modifier = Modifier
            .height(142.dp)
            .clip(CropShape)
            .padding(start = 20.dp, bottom = 20.dp)
            .rotate(TiltedImageRotation)
        painter = resourcePainter(R.drawable.image),
        contentScale = ContentScale.FillHeight,
        contentDescription = null,
    )
}
Run Code Online (Sandbox Code Playgroud)

Jan*_*ína 7

设置宽度是正确的方法,alignment我认为你只需要正确的 - 用于alignment = Alignment.CenterStart查看图像的开始而不是像第二张图片那样的中心:

Image(
    modifier = Modifier
        .height(142.dp)
        .width(58.dp)
        .padding(start = 20.dp, bottom = 20.dp)
        .rotate(TiltedImageRotation)
    painter = resourcePainter(R.drawable.image),
    contentScale = ContentScale.FillHeight,
    alignment = Alignment.CenterStart,
    contentDescription = null,
)
Run Code Online (Sandbox Code Playgroud)

如果您想按照其他答案中的建议与一些偏移量对齐,也可以这样做Alignment,而且更容易:

val density = LocalDensity.current
Image(
    alignment = Alignment { _, _, _ ->
        val xOffset = density.run { 58.dp.toPx() / 2 }.roundToInt()
        IntOffset(x = -xOffset, 0)
    }
)
Run Code Online (Sandbox Code Playgroud)