Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 437
ameencarpenter Avatar asked Apr 04 '21 14:04

ameencarpenter


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

like image 134
Gabriele Mariotti Avatar answered Oct 19 '22 09:10

Gabriele Mariotti