I'm trying to implement simple image cropper with compose. The overlay can be resized and drag over the image. The problem is, it can be dragged out of the image and out of screen too. How to set limits for the overlay to move and resized over the image only?
The updated code
@Composable
fun ImageCrooper() {
var size by remember { mutableStateOf(Size.Zero) }
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
var height by remember { mutableStateOf(140f) }
var width by remember { mutableStateOf(140f) }
BoxWithConstraints(
Modifier
.fillMaxWidth()
.height(240.dp)
.onSizeChanged {
size = it.toSize()
}
) {
Image(
modifier = Modifier
.fillMaxSize(),
contentScale = ContentScale.Crop,
painter = rememberAsyncImagePainter(
model = "https://i.picsum.photos/id/216/200/200.jpg?hmac=7Weas8POu49YrmUyJ6tWdqVMx-hw6lryzl8HnHZBzjc"
),
contentDescription = "A Content description",
)
BoxWithConstraints(
modifier = Modifier
.offset {
IntOffset(offsetX.roundToInt(), offsetY.roundToInt())
}
.height(height.dp)
.width(width.dp)
) {
// move the overlay
Box(
Modifier
.background(Color.Black.copy(0.6f))
.fillMaxSize()
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
offsetY = (offsetY + dragAmount.y).coerceIn(0f, 230f)
offsetX = (offsetX + dragAmount.x).coerceIn(0f, size.width)
}
}
)
// resize the overlay
Box(
Modifier
.align(Alignment.BottomEnd)
.background(Color.White)
.height(20.dp)
.width(20.dp)
.pointerInput(Unit) {
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
width = (width + dragAmount.x).coerceIn(140f, size.width - width)
height = (height + dragAmount.y).coerceIn(140f, size.height - height)
}
}
)
}
}
}