29

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
  • 1,859
  • 1
  • 18
  • 37

3 Answers3

60

With Jetpack Compose BETA02:

Box(
    modifier = Modifier
        .background(
            brush = Brush.verticalGradient(
                colors = listOf(
                    MaterialTheme.colors.primary,
                    MaterialTheme.colors.primaryVariant
                )
            )
        )
) {
    Content()
}
Luis Fer Garcia
  • 1,948
  • 1
  • 13
  • 12
14

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,110
  • 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
  • 828
  • 9
  • 10