60

Is it possible to draw a gradient over an image drawable using Jetpack Compose?

fun HeroCover() {
    Column {
        val image = +imageResource(R.drawable.edge_of_tomorrow_poster)
        Container(modifier = Height(440.dp) wraps Expanded) {
            Clip(shape = RoundedCornerShape(8.dp)) {
                DrawImage(image = image)
            }
        }
    }
}

I want to have a translucent gradient drawn on top of the image.

AouledIssa
  • 2,528
  • 2
  • 22
  • 39

4 Answers4

119

Try this:

Box(
    modifier = Modifier
        .background(
            brush = Brush.verticalGradient(
                colors = listOf(
                    MaterialTheme.colors.primary,
                    MaterialTheme.colors.primaryVariant
                )
            )
        )
) {
    Content()
}
Luis Fer Garcia
  • 3,168
  • 3
  • 15
  • 13
16

Here is an example of how a LinearGradientShader is used in Compose on a paint object. I imagine you could use something similar to get what you want

https://gist.github.com/lelandrichardson/35b2743e1acd5d672f963f92aca57d4a#file-shimmer-kt-L83

Update: Here's another way to do it that I stumbled on in kotlin lang slack channels -

Box(
    modifier = Modifier
        .preferredSize(500.dp, 500.dp)
        .drawBackground(
            HorizontalGradient(
                0.0f to Color.Red,
                0.5f to Color.Green,
                1.0f to Color.Blue,
                startX = Px.Zero,
                endX = 500.dp.toPx()
            )
        )
)

Source: https://kotlinlang.slack.com/archives/CJLTWPH7S/p1590430288092800

Vinay Gaba
  • 1,156
  • 3
  • 12
  • 26
2

Here is a way inspired from the Jetsnack sample code: Replace transparent & darkChocolate by your own colors.

@Composable
fun GradientView(modifier: Modifier = Modifier) {
    Box(modifier = modifier.verticalGradientBackground(listOf(transparent, darkChocolate)))
}

fun Modifier.verticalGradientBackground(
        colors: List<Color>
) = drawWithCache {
    val gradient = VerticalGradient(startY = 0.0f, endY = size.width, colors = colors)
    onDraw {
        drawRect(brush = gradient)
    }
}
sachadso
  • 848
  • 9
  • 10
0

You can use below code:

  @Composable
  fun GradientBackground() {
    val gradientBrush = Brush.verticalGradient(
        colors = listOf(Color.Blue, Color.Red), // Gradient colors
        startY = 0f, // Starting Y position of the gradient
        endY = 500f // Ending Y position of the gradient
    )

    Text(
        modifier = Modifier
            .fillMaxSize()
            .background(brush = gradientBrush),
        text = "Hello, Gradient Text",
        color = Color.White
    )
 }
Ravi Vaghela
  • 3,420
  • 2
  • 23
  • 51