Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Jetpack compose gradient

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.

like image 347
AouledIssa Avatar asked Dec 15 '19 21:12

AouledIssa


3 Answers

Try this:

Box(
    modifier = Modifier
        .background(
            brush = Brush.verticalGradient(
                colors = listOf(
                    MaterialTheme.colors.primary,
                    MaterialTheme.colors.primaryVariant
                )
            )
        )
) {
    Content()
}
like image 160
Luis Fer Garcia Avatar answered Nov 11 '22 11:11

Luis Fer Garcia


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

like image 27
Vinay Gaba Avatar answered Nov 11 '22 10:11

Vinay Gaba


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)
    }
}
like image 2
sachadso Avatar answered Nov 11 '22 11:11

sachadso