Created
September 24, 2024 21:21
-
-
Save Sypers/3cbe72a053cd1bc3d98bd6671a7682f5 to your computer and use it in GitHub Desktop.
A Customizable scrollbar that can be applied in any composable in jetpack compose that supports a Modifier. The scrollbar is not interactive and is just an indicator for the current position of the ScrollState.
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
@Composable | |
fun Modifier.verticalScrollBar( | |
state: ScrollState, | |
color: Color = Color.Gray, | |
ratio: Float = 3f, | |
width: Dp = 8.dp, | |
alwaysOn: Boolean = false | |
): Modifier { | |
val targetAlpha = if (state.isScrollInProgress || alwaysOn) 1f else 0f | |
val duration = if (state.isScrollInProgress) 150 else 500 | |
val alpha by animateFloatAsState( | |
targetValue = targetAlpha, | |
animationSpec = tween(durationMillis = duration), label = "scrollBarAlpha" | |
) | |
return drawWithContent { | |
drawContent() | |
val needDrawScrollbar = state.isScrollInProgress || alpha > 0.0f | |
val barHeight = (this.size.height / ratio) | |
val barRange = (this.size.height - barHeight) / state.maxValue | |
if (needDrawScrollbar) { | |
val position = state.value * barRange | |
drawRect( | |
color = color.copy(alpha = alpha), | |
topLeft = Offset(this.size.width - width.toPx(), position), | |
size = Size(width.toPx(), barHeight) | |
) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment