Home > Blockchain >  Drag Composable only inside given boundries with Jetpack Compose
Drag Composable only inside given boundries with Jetpack Compose

Time:06-17

so I have a black box (rectangle) inside another box (boundary) and the rectangle is set as draggable

But now I can drag the rectangle around the whole window, but I want that if the rectangle "leaves" the boundary it should disappear behind it. Is there another modifier I can use for it?

Here a bit context:

My code looks like this:

MaterialTheme {
        Box(modifier = Modifier
            .size(500f.dp)
            .border(2f.dp, Color.Black, RectangleShape)
        ){
            Box(modifier = Modifier
                .offset { IntOffset(offsetX.roundToInt(), 0) }
                .draggable(
                    orientation = Orientation.Horizontal,
                    state = rememberDraggableState { delta ->
                        offsetX  = delta
                    }
                )
                .background(Color.Blue)
                .size(100f.dp)
            ){
                Text("Hello")
            }
        }
    }

When I drag the rectangle outside the boundary it looks like this:

Unwanted behavior

But it should more like this:

Wanted behavior

CodePudding user response:

On the composable whose contents you want to clip add the clipToBounds() modifier.

Box(modifier = Modifier
    .size(500f.dp)
    .border(2f.dp, Color.Black, RectangleShape)
    .clipToBounds()
)
  • Related