简体   繁体   中英

Drag Composable only inside given boundries with Jetpack Compose

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:

不良行为

But it should more like this:

通缉行为

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()
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM