How to make a surface background half transparent in jetpack compose, but not the content?

Viewed 18184

I want to achieve this layout:

enter image description here

In XML I would add an image in a relative layout with match_parent attributes, then a view with a black half-transparent background set to match_parent as well, then the content.

In compose I made this composeable:

@Composable
fun ImageCover(resourceId: Int, alpha: Float = 0.5f, content: @Composable () -> Unit) {
    Box(modifier = Modifier.fillMaxSize()) {
        Image(
            painter = painterResource(id = resourceId),
            contentDescription = null,
            modifier = Modifier.fillMaxSize(),
            contentScale = ContentScale.Crop
        )
        Surface(
            color = Color.Black, modifier = Modifier
                .fillMaxSize()
                .alpha(alpha)
        ) {
            content()
        }
    }
}

But the problem is alpha is applied to the surface and its content. So no matter what I put in the content, even if it's another surface with a background, will also be half transparent. Here, for example, the two sentences and two components at the bottom will be half transparent as well.

1 Answers

The background color of the Surface is based on the color attribute.
Apply the alpha to the color property instead of the Modifier.

Something like:

   Surface(
        color = Color.Black.copy(alpha = 0.6f), 
        modifier = Modifier.fillMaxSize()
    ){ 
       //....
    } 

enter image description here

Related