Configure touch dragging for the UI element in both orientations.
Draggable2DSample
@Composable
fun Draggable2DSample() {
// Draw a box that has a a grey background
// with a red square that moves along 300.dp dragging in both directions
val max = 200.dp
val min = 0.dp
val (minPx, maxPx) = with(LocalDensity.current) { min.toPx() to max.toPx() }
// this is the offset we will update while dragging
var offsetPositionX by remember { mutableStateOf(0f) }
var offsetPositionY by remember { mutableStateOf(0f) }
Box(
modifier =
Modifier.width(max)
.height(max)
.draggable2D(
state =
rememberDraggable2DState { delta ->
val newValueX = offsetPositionX + delta.x
val newValueY = offsetPositionY + delta.y
offsetPositionX = newValueX.coerceIn(minPx, maxPx)
offsetPositionY = newValueY.coerceIn(minPx, maxPx)
}
)
.background(Color.LightGray)
) {
Box(
Modifier.offset {
IntOffset(offsetPositionX.roundToInt(), offsetPositionY.roundToInt())
}
.size(50.dp)
.background(Color.Red)
)
}
}