I'm trying to drag a shape on a `Canvas`. I use `M...
# compose
r
I'm trying to drag a shape on a
Canvas
. I use
Modifier.draggable
, but the handler does not have access to the Canvas's width, to constrain the drag. How can I pass the Canvas's width to the drag handler? Example in thread...
Example:
Copy code
val offset = remember { mutableStateOf(0f) }
val dragState = rememberDraggableState { dx ->
    offset.value = (offset.value + dx).coerceIn(0f, ???) // canvas width?
}
Canvas(Modifier.fillMaxWidth().height(40.dp)
        .draggable(orientation = Orientation.Horizontal,
                   state = dragState)) {
    // this.size.width is available here. How to pass to the drag handler?
    drawThing(offset)
}
s
You can use
Modifier.onSizeChanged
on the
Canvas
to get it's size:
Copy code
val size by remember { mutableStateOf(0.dp) }
val dragState = rememberDraggableState { dx ->
    offset.value = (offset.value + dx).coerceIn(0f, size.width)
}
Canvas(modifier = Modifier
          ...
          .onSizeChanged { size = it }
          ...
)
👍 1
r
Great, thanks guys!