Reputation: 41
Let's say I want to show a composable view with an image. Instead of an original image I would like to trim part of the image away, for example 20% from the right edge. How would I do this? Can I use a .clip-modifier with a custom shape?
Upvotes: 1
Views: 985
Reputation: 88142
You can crop it with a shape, as @Thracian suggests, but in that case the view size won't change. For example, if you put it in Row
, you will have an unexpected padding to next item.
Instead, you can use Modifier.layout
to actually reduce the size of the view, and clip it with RectangleShape
, since by default Compose views are not clip to bounds.
Image(
painter = painterResource(id = R.drawable.my_image_1),
contentDescription = null,
modifier = Modifier
.clip(RectangleShape)
.layout { measurable, constraints ->
val placeable = measurable.measure(constraints)
layout(width = placeable.width * 8 / 10, height = placeable.height) {
placeable.place(0, 0)
}
}
)
Upvotes: 2
Reputation: 67218
You can create your own shape and clip using that shape as
private val cropShape = GenericShape { size: Size, layoutDirection: LayoutDirection ->
addRect(Rect(0f, 0f, size.width * .8f, size.height))
}
0.8 is arbitrary number, you can customize your Rectangle as you wish
Image(
modifier = Modifier.clip(cropShape),
painter = bitmap,
contentDescription = null
)
The one on top without clip modifier, the one at the bottom is clipped with Modifier.clip(cropShape)
Upvotes: 2