pavankumar
02/14/2022, 8:24 AMCode snipper in the thread.
Colton Idle
02/14/2022, 12:03 PMpavankumar
02/14/2022, 12:05 PMBoxWithConstraints(Modifier.fillMaxSize()) {
val offset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) }
val width = constraints.maxWidth.toFloat()
val height = constraints.maxHeight.toFloat()
Box(
Modifier
.offset { IntOffset(offset.value.x.roundToInt(), offset.value.y.roundToInt()) }
.background(Color.Blue)
.size(50.dp)
.pointerInput(Unit) {
val decay = SplineBasedFloatDecayAnimationSpec(this)
coroutineScope {
val tracker = VelocityTracker()
detectDragGestures(onDragEnd = {
val velocity = Offset(tracker.calculateVelocity().x, tracker.calculateVelocity().y)
val targetX = decay.getTargetValue(offset.value.x, velocity.x)
val targetY = decay.getTargetValue(offset.value.y, velocity.y)
val calculatedX = if (targetX.absoluteValue < (width - targetX.absoluteValue).absoluteValue) {
0f
} else {
width
}
val calculatedY = if (targetY.absoluteValue < (height - targetY.absoluteValue).absoluteValue) {
0f
} else {
height
}
offset.updateBounds(
Offset(0f, 0f),
Offset(width - size.width, height - size.height.toFloat())
)
launch {
offset.animateTo(Offset(calculatedX, calculatedY), SpringSpec<Offset>(), velocity)
}
}, onDrag = { change, dragAmount ->
change.consumeAllChanges()
tracker.addPosition(change.uptimeMillis, change.position)
launch {
offset.snapTo(
Offset(
offset.value.x + dragAmount.x,
offset.value.y + dragAmount.y
)
)
}
})
}
}
)
}