Created
November 14, 2021 09:22
-
-
Save EmmanuelGuther/6075494d1f0599fe76a1e6cd0c6e42e5 to your computer and use it in GitHub Desktop.
Jetpack compose gradient modifier
This file contains hidden or 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
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 | |
) | |
} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
modifier =Modifier
.gradientBackground(listOf(Color.Red, Color.Green), angle = 45f)