package
com.geeksforgeeks.angledgradient
import
android.os.Bundle
import
androidx.activity.ComponentActivity
import
androidx.activity.compose.setContent
import
androidx.compose.foundation.layout.Arrangement
import
androidx.compose.foundation.layout.Box
import
androidx.compose.foundation.layout.Column
import
androidx.compose.foundation.layout.fillMaxSize
import
androidx.compose.material.*
import
androidx.compose.ui.Alignment
import
androidx.compose.ui.Modifier
import
androidx.compose.ui.draw.drawBehind
import
androidx.compose.ui.geometry.Offset
import
androidx.compose.ui.graphics.Brush
import
androidx.compose.ui.graphics.Color
import
java.lang.Math.*
import
kotlin.math.pow
import
kotlin.math.sqrt
class
MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super
.onCreate(savedInstanceState)
setContent {
Scaffold(
topBar = { TopAppBar(title = { Text(
"GFG | Angled Background Gradient"
, color = Color.White) }, backgroundColor = Color(
0xff0f9d58
)) },
content = {
Column(Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {
Box(Modifier.fillMaxSize().gradientBackground(listOf(Color.Red, Color.Green), angle = 45f))
}
}
)
}
}
private
fun Modifier.gradientBackground(colors: List<Color>, angle: Float) =
this
.then(
Modifier.drawBehind {
val angleRad = angle / 180f * PI
val x = kotlin.math.cos(angleRad).toFloat()
val y = kotlin.math.sin(angleRad).toFloat()
val radius = 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
)
}
)
}