Compose Modifier

graphicsLayer

A Modifier.Element that makes content draw into a draw layer.

AnimateFadeIn

@Composable
fun AnimateFadeIn() {
    val animatedAlpha = remember { Animatable(0f) }
    Text(
        "Hello World",
        Modifier.graphicsLayer {
            alpha = animatedAlpha.value
            clip = true
        },
    )
    LaunchedEffect(animatedAlpha) { animatedAlpha.animateTo(1f) }
}

ChangeOpacity

@Composable
fun ChangeOpacity() {
    Text("Hello World", Modifier.graphicsLayer(alpha = 0.5f, clip = true))
}

CompositingStrategyModulateAlpha

@Composable
fun CompositingStrategyModulateAlpha() {
    Canvas(
        modifier =
            Modifier.size(100.dp)
                .background(Color.Black)
                .graphicsLayer(
                    alpha = 0.5f,
                    compositingStrategy = CompositingStrategy.ModulateAlpha,
                )
    ) {
        // Configuring an alpha less than 1.0 and specifying
        // CompositingStrategy.ModulateAlpha ends up with the overlapping region
        // of the 2 draw rect calls to blend transparent blue and transparent red
        // against the black background instead of just transparent blue which is what would
        // occur with CompositingStrategy.Auto or CompositingStrategy.Offscreen
        inset(0f, 0f, size.width / 3, size.height / 3) { drawRect(color = Color.Red) }
        inset(size.width / 3, size.height / 3, 0f, 0f) { drawRect(color = Color.Blue) }
    }
}

CompositingStrategyOffscreenLayerOutsets

@Composable
fun CompositingStrategyOffscreenLayerOutsets() {
    Box(Modifier.size(100.dp).graphicsLayer(alpha = 0.5f, outsets = LayerOutsets(100.dp))) {
        // Configuring an alpha less than 1.0 has promoted the layer to an offscreen buffer thus
        // implicitly clipping
        // the layer to its bounds. The inner box draws a Rect which extends beyond the layout
        // bounds of the outer
        // box. LayerOutsets are provided to the layer that is promoted to the offscreen buffer to
        // extend its visual bounds
        // to avoid clipping the content drawn by its children.
        Box(
            Modifier.fillMaxSize().drawBehind {
                drawRect(
                    topLeft = Offset(100f, 100f),
                    brush = SolidColor(Color.Red),
                    size = Size(800f, 500f),
                )
            }
        )
    }
}

Last updated: