@Composable
fun DraggableBox() {
val boxSize = 100.dp
val scope = rememberCoroutineScope()
val offsetX = remember { Animatable(0f) }
val offsetY = remember { Animatable(0f) }
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.LightGray)
.pointerInput(Unit) {
detectDragGestures(
onDragEnd = {
// Snap to nearest corner or target location
scope.launch {
offsetX.animateTo(300f)
offsetY.animateTo(500f)
}
},
onDrag = { change, dragAmount ->
change.consume()
scope.launch {
offsetX.snapTo(offsetX.value + dragAmount.x)
offsetY.snapTo(offsetY.value + dragAmount.y)
}
}
)
}
) {
Box(
modifier = Modifier
.offset { IntOffset(offsetX.value.roundToInt(), offsetY.value.roundToInt()) }
.size(boxSize)
.background(Color.Blue, RoundedCornerShape(8.dp))
)
}
}