Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Forked from dovahkiin98/FadingEdge.kt
Last active April 12, 2023 19:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/af4b0388e6eab8ecaa888ea2f15088cc to your computer and use it in GitHub Desktop.
Save hrules6872/af4b0388e6eab8ecaa888ea2f15088cc to your computer and use it in GitHub Desktop.
A Jetpack Compose implementation of the `fadingEdge` effect
fun Modifier.horizontalFadingEdge(
scrollState: ScrollState,
length: Dp,
edgeColor: Color? = null,
) = composed(
debugInspectorInfo {
name = "length"
value = length
}
) {
val color = edgeColor ?: MaterialTheme.colors.surface
drawWithContent {
val lengthValue = length.toPx()
val scrollFromStart = scrollState.value
val scrollFromEnd = scrollState.maxValue - scrollState.value
val startFadingEdgeStrength = lengthValue * (scrollFromStart / lengthValue).coerceAtMost(1f)
val endFadingEdgeStrength = lengthValue * (scrollFromEnd / lengthValue).coerceAtMost(1f)
drawContent()
drawRect(
brush = Brush.horizontalGradient(
colors = listOf(
color,
Color.Transparent,
),
startX = 0f,
endX = startFadingEdgeStrength,
),
size = Size(
startFadingEdgeStrength,
this.size.height,
),
)
drawRect(
brush = Brush.horizontalGradient(
colors = listOf(
Color.Transparent,
color,
),
startX = size.width - endFadingEdgeStrength,
endX = size.width,
),
topLeft = Offset(x = size.width - endFadingEdgeStrength, y = 0f),
)
}
}
fun Modifier.verticalFadingEdge(
scrollState: ScrollState,
length: Dp,
edgeColor: Color? = null,
) = composed(
debugInspectorInfo {
name = "length"
value = length
}
) {
val color = edgeColor ?: MaterialTheme.colors.surface
drawWithContent {
val lengthValue = length.toPx()
val scrollFromTop = scrollState.value
val scrollFromBottom = scrollState.maxValue - scrollState.value
val topFadingEdgeStrength = lengthValue * (scrollFromTop / lengthValue).coerceAtMost(1f)
val bottomFadingEdgeStrength = lengthValue * (scrollFromBottom / lengthValue).coerceAtMost(1f)
drawContent()
drawRect(
brush = Brush.verticalGradient(
colors = listOf(
color,
Color.Transparent,
),
startY = 0f,
endY = topFadingEdgeStrength,
),
size = Size(
this.size.width,
topFadingEdgeStrength
),
)
drawRect(
brush = Brush.verticalGradient(
colors = listOf(
Color.Transparent,
color,
),
startY = size.height - bottomFadingEdgeStrength,
endY = size.height,
),
topLeft = Offset(x = 0f, y = size.height - bottomFadingEdgeStrength),
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment