Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jetpack compose gradient modifier
fun Modifier.gradientBackground(colors: List<Color>, angle: Float) = this.then(
Modifier.drawBehind {
val angleRad = angle / 180f * PI
val x = kotlin.math.cos(angleRad).toFloat() //Fractional x
val y = kotlin.math.sin(angleRad).toFloat() //Fractional y
val radius:Float = kotlin.math.sqrt(
((size.width.pow(2) + size.height.pow(2))) / 2f)
val offset = center + Offset(x * radius, y * radius)
val exactOffset = Offset(
x = kotlin.math.min(offset.x.coerceAtLeast(0f), size.width),
y = size.height - kotlin.math.min(offset.y.coerceAtLeast(0f), size.height)
)
drawRect(
brush = Brush.linearGradient(
colors = colors,
start = Offset(size.width, size.height) - exactOffset,
end = exactOffset
),
size = size
)
}
)
@EmmanuelGuther

This comment has been minimized.

Copy link
Owner Author

@EmmanuelGuther EmmanuelGuther commented Nov 14, 2021

USE ---->  

modifier =Modifier
.gradientBackground(listOf(Color.Red, Color.Green), angle = 45f)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment