Skip to content

Instantly share code, notes, and snippets.

@EmmanuelGuther
Created November 14, 2021 09:22
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 EmmanuelGuther/6075494d1f0599fe76a1e6cd0c6e42e5 to your computer and use it in GitHub Desktop.
Save EmmanuelGuther/6075494d1f0599fe76a1e6cd0c6e42e5 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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