Created
August 5, 2022 04:01
-
-
Save fvilarino/0a1b81b459e4aa2b525a0123c14bb05e to your computer and use it in GitHub Desktop.
Circular Carousel with Correct Drag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun Modifier.drag( | |
state: CircularCarouselState, | |
) = pointerInput(Unit) { | |
val decay = splineBasedDecay<Float>(this) | |
coroutineScope { | |
while (true) { | |
val pointerInput = awaitPointerEventScope { awaitFirstDown() } | |
state.stop() | |
val tracker = VelocityTracker() | |
val degreesPerPixel = 180f / size.width.toFloat() | |
awaitPointerEventScope { | |
// 1 | |
val isTopHalf = pointerInput.position.y < size.height / 2f | |
// 2 | |
val signum = when { | |
isTopHalf -> -1f | |
else -> 1f | |
} | |
horizontalDrag(pointerInput.id) { change -> | |
// 3 | |
val horizontalDragOffset = state.angle + signum * change.positionChange().x * degreesPerPixel | |
launch { | |
state.snapTo(horizontalDragOffset) | |
} | |
tracker.addPosition(change.uptimeMillis, change.position) | |
if (change.positionChange() != Offset.Zero) change.consume() | |
} | |
val velocity = tracker.calculateVelocity().x | |
val targetAngle = decay.calculateTargetValue( | |
state.angle, | |
// 4 | |
signum * velocity * degreesPerPixel, | |
) | |
launch { | |
state.decayTo( | |
angle = targetAngle, | |
// 5 | |
velocity = signum * velocity * degreesPerPixel, | |
) | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment