Primož Ivančič
Primož Ivančič

Reputation: 2366

How to create oval gradient in Jetpack Compose

I need oval gradient for a background, but all I'm able to get is perfectly round gradient with Brush.radialGradient(..):

Modifier
    .fillMaxSize()
    .background(
        brush = Brush.radialGradient(
            colors = listOf(Color(0xFFffffff), Color(0xFF000000)),
        ),
    )

This is what I need (the shape of the oval must of course be aligned with screen size ratio):

This is what I need

But all I am able to produce, is this:

This is what I am able to produce

Any ideas on how can I solve this?

Upvotes: 3

Views: 5056

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 87744

Radical gradient shouldn't stretch like this, it determine pixel color depending on distance from the center.

I'm not sure why there's no "Oval" gradient, but it's missing from android itself, and compose is just an interlayer here.

What is usually done in the android is just scaling the view. You can do it on compose too:

BoxWithConstraints(
    Modifier
        .fillMaxSize()
) {
    val aspectRatio = maxWidth / maxHeight
    Box(
        Modifier
            .fillMaxSize()
            .scale(maxOf(aspectRatio, 1f), maxOf(1 / aspectRatio, 1f))
            .background(
                brush = Brush.radialGradient(
                    colors = listOf(Color(0xFFffffff), Color(0xFF000000)),
                ),
            )
    )
}

Here I'm using BoxWithConstraints to get maxWidth and maxHeight, in order to calculate needed scale.

enter image description here

Upvotes: 8

Related Questions