Home > OS >  Rectangular gradient in Compose
Rectangular gradient in Compose

Time:12-08

I need to do a rectangular gradient border over an image, the edges should be of dark background color and closer to the center it should fade away to transparent. I was thinking about using radial gradient as I can make it transparent in the center.

val gradientBrush = Brush.radialGradient(
    colors = listOf(Color.Transparent, MaterialTheme.colors.background)
)
Image(
    painter = ...,
    contentScale = ContentScale.Inside,
    modifier = Modifier
        .clip(RoundedCornerShape(48.dp))
        .border(
            180.dp,
            gradientBrush ,
            RoundedCornerShape(48.dp)
        )
        .wrapContentHeight()
        .fillMaxWidth()
)

But this gives me a gradient in the form of a circle. I guess that with scaling I could make it oval. But I wonder is there any way I can make it rectangular? I was thinking along the lines of placing four gradients around the image, but they would overlap.

CodePudding user response:

You can use linear gradient with stops, so middle part of your image will be transparent.

val gradientBrush = Brush.linearGradient(
    0f to MaterialTheme.colors.background,
    0.4f to Color.Transparent,
    0.6f to Color.Transparent,
    1f to MaterialTheme.colors.background,
)

By default it's horizontal, but you can use verticalGradient instead, or specify start/end parameters for custom direction.

  • Related