Muhammad Ahmed AbuTalib
Muhammad Ahmed AbuTalib

Reputation: 4312

Surface color alpha , also affects the content color?

I couldn't find this behavior documented anywhere

Lets suppose you have a Surface composable like below

Surface(color = MaterialTheme.colorScheme.primary) {
        Icon( Icons.Filled.Abc, contentDescription ="" )
    }

The resulting output has the correct colors for the background of the Icon (which is the primary) and the Icon color itself which is the contentColorFor for primary (onPrimary)

However once I apply some alpha on the surface's color , the Icon's color changes too

    Surface(color = MaterialTheme.colorScheme.primary.copy(alpha=0.5f)) {
        Icon( Icons.Filled.Abc, contentDescription ="" )
    }

Here I am expecting only the Surface's color to change , but the content color also changes. This implies that there is some sort of connection between color and contentColor about which I couldn't find any documentation.

I thought that the Surface composable simply picks up the onXXX color as the contentColor , but apparently more is happening behind the scenes.

Any one has any explanations ?

Upvotes: 0

Views: 25

Answers (1)

Lino
Lino

Reputation: 6160

This is the expected behaviour.

If you look at Surface's source code below, you can see that it leverages CompositionLocalProvider with LocalContentColor set to contentColor (content color derives from color parameter). This propagates color changes to the composable function proved through the content parameter.

fun Surface(
    modifier: Modifier = Modifier,
    shape: Shape = RectangleShape,
    color: Color = MaterialTheme.colorScheme.surface,
    contentColor: Color = contentColorFor(color),
    tonalElevation: Dp = 0.dp,
    shadowElevation: Dp = 0.dp,
    border: BorderStroke? = null,
    content: @Composable () -> Unit
) {
    val absoluteElevation = LocalAbsoluteTonalElevation.current + tonalElevation
    CompositionLocalProvider(
        LocalContentColor provides contentColor,
        LocalAbsoluteTonalElevation provides absoluteElevation
    ) {
        Box(

Upvotes: 0

Related Questions