You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jetpack Compose中裁剪图片?能否垂直切半且不改变原图宽高?

实现方案

当然可以,不需要修改图片本身的宽高配置,通过自定义裁切Shape就能实现和clip(CutCornerShape(50.dp))完全一致的调用体验,且原有布局中图片的占位尺寸不会发生任何变化。

方案1:自定义Shape复用裁切逻辑

如果你需要在多处使用垂直裁切一半的效果,推荐自定义Shape实现:

class VerticalHalfShape(private val keepTopHalf: Boolean = true) : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline {
        val halfHeight = size.height / 2
        val cropRect = if (keepTopHalf) {
            Rect(0f, 0f, size.width, halfHeight)
        } else {
            Rect(0f, halfHeight, size.width, size.height)
        }
        return Outline.Rectangle(cropRect)
    }
}

调用方式和系统自带Shape完全一致,直接传入clipModifier即可:

Image(
    painter = painterResource(id = R.drawable.your_image),
    contentDescription = null,
    // 传入keepTopHalf = false代表裁掉上半部分,保留下半部分
    modifier = Modifier.clip(VerticalHalfShape(keepTopHalf = false))
)

方案2:单次使用快速实现

如果只需要单次使用该裁切效果,可以直接用graphicsLayer搭配clipRect实现,不需要额外自定义类:

Image(
    painter = painterResource(id = R.drawable.your_image),
    contentDescription = null,
    modifier = Modifier.graphicsLayer {
        // 裁掉下半部分,仅保留上半部分
        clipRect(top = 0f, bottom = size.height / 2, clip = true)
        // 若要裁掉上半部分保留下半部分,替换为下面的代码即可
        // clipRect(top = size.height / 2, bottom = size.height, clip = true)
    }
)

内容的提问来源于stack exchange,提问作者Someone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 05:39:05