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.
Try this:
Box(
    modifier = Modifier
        .background(
            brush = Brush.verticalGradient(
                colors = listOf(
                    MaterialTheme.colors.primary,
                    MaterialTheme.colors.primaryVariant
                )
            )
        )
) {
    Content()
}
                        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
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)
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With