Skip to content

Instantly share code, notes, and snippets.

@jisungbin
Last active October 18, 2023 18:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jisungbin/e1e0e63e0215a4a9fdb9386c868f3829 to your computer and use it in GitHub Desktop.
Save jisungbin/e1e0e63e0215a4a9fdb9386c868f3829 to your computer and use it in GitHub Desktop.
Jetpack Compose horizontal fading edges with ScrollableState.
@Stable
fun Modifier.drawHorizontalFadingEdges(
target: Color = Color.White,
width: Dp = 10.dp,
scrollState: ScrollableState,
) =
if (!scrollState.canScrollForward && !scrollState.canScrollBackward) this
else drawWithCache {
val gradientWidth = width.toPx()
val startGradientColors = listOf(target, Color.Transparent)
val endGradientColors = listOf(Color.Transparent, target)
val startGradientBrush =
Brush.linearGradient(
colors = startGradientColors,
start = Offset(x = 0f, y = size.height), // why not Offset.Zero?
end = Offset(x = gradientWidth, y = size.height),
)
val endGradientBrush =
Brush.linearGradient(
colors = endGradientColors,
start = Offset(x = size.width - gradientWidth, y = size.height),
end = Offset(x = size.width, y = size.height),
)
onDrawWithContent {
drawContent()
if (scrollState.canScrollBackward) drawRect(brush = startGradientBrush, size = size)
if (scrollState.canScrollForward) drawRect(brush = endGradientBrush, size = size)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment