Home > Enterprise >  How to apply translucent gradient on an Image in Android Jetpack Compose?
How to apply translucent gradient on an Image in Android Jetpack Compose?

Time:11-27

In Android Jetpack Compose, does anyone knows how to make an Image's left side slowly fading to transparent towards right side? Thanks!

Edit: Sorry, I mean making an image fading like this in Compose, probably with blend mode? But not sure how to do that..

Expected outcome:

Image fading to transparent sample

CodePudding user response:

You could place a Box over the image and add a background gradient to the Box. You will have to set the size of the Box though to be the same as the image. In this example I don't bother setting the Box size correctly. I'll leave that up to you:

Here's the image I used:

https://adelaidevet.com.au/sites/default/files/archive/files/images/cat-ginger-eyes-closed_0.jpg

val screenWidth = LocalConfiguration.current.screenWidthDp

Box(modifier = Modifier.fillMaxWidth().wrapContentHeight()) {
    Image(
        painterResource(R.drawable.cat),
        contentDescription = "",
        contentScale = ContentScale.FillWidth,
        modifier = Modifier.fillMaxWidth()
    )

    Box(
        modifier = Modifier
            .requiredWidth(screenWidth.dp)
            .requiredHeight(310.dp)
            .background(
                brush = Brush.horizontalGradient(
                    startX = 0f,
                    endX = 700f,
                    colors = listOf(
                        Color.Transparent,
                        Color(0xD7525252),

                    )
                )
            )
    ) {

    }
}

CodePudding user response:

Just found an answer from How to add fading edge effect to Android Jetpack Compose Column or Row?

"Color.Black" means area that reveal the image.

Thanks guys!

Image(
    painterResource(R.drawable.cat),
    contentDescription = null,
    contentScale = ContentScale.Crop,
    modifier = Modifier
        // Workaround to enable alpha compositing
        .graphicsLayer { alpha = 0.99f }
        .drawWithContent {
            val colors = listOf(
                Color.Black,
                Color.Transparent
            )
            drawContent()
            drawRect(
                brush = Brush.horizontalGradient(colors),
                blendMode = BlendMode.DstIn
            )
        }
)
  • Related