Composable Function

AndroidEmbeddedExternalSurface

Provides a dedicated drawing Surface embedded directly in the UI hierarchy.

AndroidEmbeddedExternalSurfaceColors

@Sampled
@Composable
fun AndroidEmbeddedExternalSurfaceColors() {
    AndroidEmbeddedExternalSurface(modifier = Modifier.fillMaxWidth().height(400.dp)) {
        // Resources can be initialized/cached here

        // A surface is available, we can start rendering
        onSurface { surface, width, height ->
            var w = width
            var h = height

            // Initial draw to avoid a black frame
            surface.lockCanvas(Rect(0, 0, w, h)).apply {
                drawColor(Color.Yellow.toArgb())
                surface.unlockCanvasAndPost(this)
            }

            // React to surface dimension changes
            surface.onChanged { newWidth, newHeight ->
                w = newWidth
                h = newHeight
            }

            // Cleanup if needed
            surface.onDestroyed {}

            // Render loop, automatically cancelled on surface destruction
            while (true) {
                withFrameNanos { time ->
                    surface.lockCanvas(Rect(0, 0, w, h)).apply {
                        val timeMs = time / 1_000_000L
                        val t = 0.5f + 0.5f * sin(timeMs / 1_000.0f)
                        drawColor(lerp(Color.Yellow, Color.Red, t).toArgb())
                        surface.unlockCanvasAndPost(this)
                    }
                }
            }
        }
    }
}
Jetpack Compose beyond MaterialFree components, screens and templates for apps that don’t look like Google’s. Copy them into your app, or let your coding agent add them.Browse for free

Content updated: