2

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

c_phil
  • 123
  • 6

1 Answers1

4

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()
)
Ma3x
  • 5,761
  • 2
  • 17
  • 22
  • I've tried that, but with no luck... I guess I have to set the bounds it should clip somehow, but have no idea how and where – c_phil Jun 16 '22 at 19:58
  • Thats interesting because I tried both on a phone and in the emulator and that is what does the trick. Can you post also the parent composable of you Box? Or is that the top (outermost) composable? – Ma3x Jun 16 '22 at 19:59
  • Yeah the (outermost) Box composable should be the parent composable which defines the boundaries – c_phil Jun 16 '22 at 20:01
  • Oh dammit I'm just stupid I put the modifier to the wrong coimposable... Now it works Sry and thanks :) – c_phil Jun 16 '22 at 20:04
  • 1
    Thats a good thing, that means it works for you as well :) – Ma3x Jun 16 '22 at 20:04