How to trim image in Jetpack Compose?

Viewed 465

Can we cut image into half vertically without messing with width and height of the image as we can cut corners using clip(CutCornerShape(50.dp))

1 Answers

clip modifier takes any Shape, you can create your own, for example like this:

object HalfSizeShape : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline = Outline.Rectangle(
        Rect(Offset.Zero, Size(size.width / 2, size.height))
    )
}

I'm not sure if I cut the right part of the image for you, but you should catch the idea.

Using the same technique, you can create any shape described by a Path. Also you can add parameters to your Shape like this:

class HalfSizeShape(val widthPart: Float) : Shape {
    override fun createOutline(
        size: Size,
        layoutDirection: LayoutDirection,
        density: Density
    ): Outline = Outline.Generic(Path().apply {
        addRect(Rect(Offset.Zero, Size(size.width * widthPart, size.height)))
    })
}

Usage:

Modifier.clip(HalfSizeShape)
Related