Apple-style, slow-drifting color fields built on the first-party MeshGradientPainter, with the performance numbers, theme wiring, and failure modes you only find after the demo works.
Every few years a visual trope jumps from one platform to another. The soft, drifting, multi-color backdrop you see behind music players, onboarding screens, and lock-screen widgets on Apple devices is one of them. On Android we have been faking it with three overlapping radialGradient brushes, a blurred bitmap, or a hand-rolled AGSL shader.
Compose now ships a first-party answer: MeshGradientPainter, in androidx.compose.ui.graphics. This post builds a production-grade backdrop with it, step by step, and then deliberately tries to break it.
The running example is a fictional “tide table” app called Lagoon. Its hero area uses a deep-ocean palette: Midnight #0B132B, Lagoon #00A6A6, Peach #FFB997, Orchid #9B5DE5, and Ember #F15BB5.
1. What a mesh gradient is, and what it is not
Linear, radial, and sweep gradients all share one limitation: color is a function of a single scalar. Distance along a line, distance from a point, or angle around a point. You can stack them, but you cannot say “make the lower-left of this surface bluer without disturbing anything else”.
A mesh gradient is a 2D grid of colored control points. The renderer blends smoothly between all of them at once, so moving or recoloring one interior point reshapes only its neighborhood.
Three ideas from the documentation matter for the rest of this post:
- Patches vs vertices. You declare
rowsandcolumnsas the number of patches. The number of vertices you must supply is(rows + 1) × (columns + 1). - Normalized coordinates.
Offset(0f, 0f)is the top-left of the draw bounds andOffset(1f, 1f)is the bottom-right. Your mesh is resolution-independent, which makes rotation, split-screen, and foldables free. - Tangents are inferred by default. If you leave Bézier control points unspecified, Compose infers tangents so adjacent patches join smoothly. Supplying them is optional polish, not a requirement.
2. MeshGradientPainter basics: rows, columns, setVertex
MeshGradientPainter is a regular Painter, so you can hand it to Modifier.paint, Image, or draw it yourself.
val painter = remember {
MeshGradientPainter(rows = 1, columns = 1, hasBicubicColor = true) {
// row col position color
setVertex(0, 0, Offset(0f, 0f), Color(0xFF00A6A6)) // top-left
setVertex(0, 1, Offset(1f, 0f), Color(0xFF9B5DE5)) // top-right
setVertex(1, 0, Offset(0f, 1f), Color(0xFF0B132B)) // bottom-left
setVertex(1, 1, Offset(1f, 1f), Color(0xFFF15BB5)) // bottom-right
}
}
Box(
Modifier
.fillMaxWidth()
.aspectRatio(16 / 9f)
.paint(painter, contentScale = ContentScale.FillBounds)
)
Two parameters deserve a senior-level note:
-
hasBicubicColor.trueuses Catmull-Rom interpolation for color and gives smoother transitions.falseuses bilinear, which the docs describe as simpler and slightly faster. Start withtrue; measure before you flip it. -
The
blockruns in a draw context. This is the single most important design fact about this API, and Section 4 and Section 7 both lean on it.
Here is how a 3 × 3 patch mesh maps onto vertex coordinates, and which vertices are safe to animate.
3. Build 1: a static 3 × 3 hero background
“3 × 3” in this post means three rows and three columns of patches, so 16 vertices. If you wanted a 3 × 3 vertex grid you would pass rows = 2, columns = 2. Mixing these up is the most common first-day bug: you supply 9 vertices, and the remaining ones stay unset.
I prefer to describe the mesh as data and loop over it. A 16-line setVertex wall is hard to review.
private val Midnight = Color(0xFF0B132B)
private val Lagoon = Color(0xFF00A6A6)
private val Peach = Color(0xFFFFB997)
private val Orchid = Color(0xFF9B5DE5)
private val Ember = Color(0xFFF15BB5)
/** Rest positions: an even 4x4 lattice in normalized space. */
private val RestGrid: List<Offset> = buildList {
for (r in 0..3) for (c in 0..3) add(Offset(c / 3f, r / 3f))
}
/** Row-major colors for the 16 vertices. */
private val HeroColors: List<Color> = listOf(
Midnight, Lagoon, Lagoon, Midnight,
Lagoon, Peach, Orchid, Lagoon,
Orchid, Ember, Peach, Orchid,
Midnight, Orchid, Ember, Midnight,
)
@Composable
fun LagoonHero(modifier: Modifier = Modifier) {
val painter = remember {
MeshGradientPainter(rows = 3, columns = 3, hasBicubicColor = true) {
for (r in 0..3) for (c in 0..3) {
val i = r * 4 + c
setVertex(r, c, RestGrid[i], HeroColors[i])
}
}
}
Box(modifier.paint(painter, contentScale = ContentScale.FillBounds))
}
Static, this is already better than three stacked brushes: one painter, one draw call from your code’s point of view, and no tuning of radii and alpha.
A static mesh looks flat when the lattice is perfectly even. Nudge a few interior rest positions off the grid, for example Offset(0.36f, 0.31f) instead of Offset(0.333f, 0.333f). Organic variation in spacing is what makes the result read as "liquid" rather than "gradient with a grid".
4. Build 2: animate vertex positions with rememberInfiniteTransition
The goal: every interior vertex drifts on its own small orbit, the loop is seamless, and nothing recomposes.
Design decisions, in order:
- Animate time, not positions. One
Floatfrom0fto1fis the clock. Each vertex derives its offset from that clock plus a unique phase. That is one animation instead of 8 interior vertices × 2 axes. - Use integer cycles per loop. If every
sinandcoscompletes a whole number of periods astgoes0 → 1, thenRepeatMode.RestartwithLinearEasingis invisible. No jump at the seam. - Pin the border. Only vertices with
rowandcolumnin1..2move. Edge vertices stay put so the mesh always covers its bounds. - Read the clock in the painter block, not in the composable body.
private const val TWO_PI = (2.0 * Math.PI).toFloat()
private fun drift(t: Float, index: Int, amplitude: Float): Offset {
val phase = index * 0.137f // unique per vertex
val dx = sin(TWO_PI * (t + phase)) // 1 cycle per loop
val dy = cos(TWO_PI * (2f * t + phase)) // 2 cycles per loop
return Offset(dx, dy) * amplitude
}
@Composable
fun LagoonDrift(
modifier: Modifier = Modifier,
periodMillis: Int = 14_000,
amplitude: Float = 0.07f,
) {
val infinite = rememberInfiniteTransition(label = "lagoon-drift")
// Keep the State object. Do NOT unwrap it with `by` here.
val clock: State<Float> = infinite.animateFloat(
initialValue = 0f,
targetValue = 1f,
animationSpec = infiniteRepeatable(
animation = tween(periodMillis, easing = LinearEasing),
repeatMode = RepeatMode.Restart,
),
label = "clock",
)
val painter = remember {
MeshGradientPainter(rows = 3, columns = 3, hasBicubicColor = true) {
val t = clock.value // draw-phase read
for (r in 0..3) for (c in 0..3) {
val i = r * 4 + c
val interior = r in 1..2 && c in 1..2
val pos = if (interior) RestGrid[i] + drift(t, i, amplitude) else RestGrid[i]
setVertex(r, c, pos, HeroColors[i])
}
}
}
Box(modifier.paint(painter, contentScale = ContentScale.FillBounds))
}
The line val t = clock.value is inside the block, which executes during draw. That means the snapshot system registers a draw-phase read, so each tick invalidates only the draw of this node. The official guide describes the same property: because the lambda runs in a DrawScope, it can observe mutable state, and you can animate positions or colors over time without reallocating shaders or bitmaps.
Keep amplitude honest
At amplitude = 0.07f a vertex moves 7% of the width. Interior neighbors are about 33% apart, so adjacent vertices can approach each other but never cross. Push amplitude past roughly half the lattice spacing divided by two and neighboring patches can fold over each other, which shows up as pinched creases. Treat spacing / 4 as an upper bound for the amplitude.
5. Build 3: tie colors to dynamic color and dark theme
A hard-coded ocean palette will clash with a user’s Material You wallpaper colors and glare in dark mode. The fix is to derive the vertex colors from the theme, and to animate theme flips instead of snapping.
I use five anchors (four corners plus a glow) and compute all 16 vertex colors from them. Anchors are animated with animateColorAsState; the resulting State<Color> objects are read inside the painter block, so after one recomposition to pick up the new target, a theme flip is a 450 ms draw-only tween. (Changing MaterialTheme.colorScheme or the dark flag does recompose AuroraMeshBackground once; what you avoid is recomposing on every tween frame.)
private class Anchors(
val topStart: State<Color>,
val topEnd: State<Color>,
val bottomStart: State<Color>,
val bottomEnd: State<Color>,
val glow: State<Color>,
)
@Composable
private fun rememberAnchors(scheme: ColorScheme, dark: Boolean): Anchors {
val spec = tween<Color>(durationMillis = 450)
// Darken surfaces in dark mode so the hero never out-shouts the content.
val base = if (dark) scheme.surface else scheme.primaryContainer
val a = animateColorAsState(scheme.primaryContainer, spec, label = "a")
val b = animateColorAsState(scheme.tertiaryContainer, spec, label = "b")
val c = animateColorAsState(base, spec, label = "c")
val d = animateColorAsState(scheme.secondaryContainer, spec, label = "d")
val g = animateColorAsState(scheme.tertiary, spec, label = "g")
// The State objects are stable across recompositions, so the holder is too.
return remember(a, b, c, d, g) { Anchors(a, b, c, d, g) }
}
private fun vertexColor(r: Int, c: Int, a: Anchors): Color {
val u = c / 3f
val v = r / 3f
val top = lerp(a.topStart.value, a.topEnd.value, u)
val bottom = lerp(a.bottomStart.value, a.bottomEnd.value, u)
val base = lerp(top, bottom, v)
// Push the two central diagonal vertices toward the glow color.
val glowWeight = when {
(r == 1 && c == 1) || (r == 2 && c == 2) -> 0.55f
(r == 1 && c == 2) || (r == 2 && c == 1) -> 0.25f
else -> 0f
}
return lerp(base, a.glow.value, glowWeight)
}
Now the final component, with the theme in, drift, and a scrim so text stays legible:
@Composable
fun AuroraMeshBackground(
modifier: Modifier = Modifier,
animate: Boolean = true,
periodMillis: Int = 14_000,
amplitude: Float = 0.07f,
content: @Composable BoxScope.() -> Unit = {},
) {
val anchors = rememberAnchors(MaterialTheme.colorScheme, isSystemInDarkTheme())
val running = animate && rememberIsStarted() && !rememberReduceMotion()
// One State<Float>. When paused, it simply holds 0f.
val clock: State<Float> =
if (running) {
rememberInfiniteTransition(label = "aurora").animateFloat(
0f, 1f,
infiniteRepeatable(tween(periodMillis, easing = LinearEasing)),
label = "clock",
)
} else remember { mutableStateOf(0f) }
val painter = remember(anchors) {
MeshGradientPainter(rows = 3, columns = 3, hasBicubicColor = true) {
val t = clock.value
for (r in 0..3) for (c in 0..3) {
val i = r * 4 + c
val interior = r in 1..2 && c in 1..2
val pos = if (interior) RestGrid[i] + drift(t, i, amplitude) else RestGrid[i]
setVertex(r, c, pos, vertexColor(r, c, anchors))
}
}
}
Box(modifier) {
Box(Modifier.matchParentSize().paint(painter, contentScale = ContentScale.FillBounds))
// Scrim: keeps body text above 4.5:1 even where the mesh passes through mid luminance.
Box(Modifier.matchParentSize().background(MaterialTheme.colorScheme.scrim.copy(alpha = 0.18f)))
content()
}
}
Two helpers cover the “stop spending battery” rules:
@Composable
private fun rememberIsStarted(): Boolean {
val owner = LocalLifecycleOwner.current // androidx.lifecycle.compose
val state by owner.lifecycle.currentStateFlow.collectAsState()
return state.isAtLeast(Lifecycle.State.STARTED)
}
@Composable
private fun rememberReduceMotion(): Boolean {
val context = LocalContext.current
var reduce by remember { mutableStateOf(readScale(context) == 0f) }
DisposableEffect(context) {
val resolver = context.applicationContext.contentResolver
val uri = Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE)
val observer = object : ContentObserver(Handler(Looper.getMainLooper())) {
override fun onChange(selfChange: Boolean) { reduce = readScale(context) == 0f }
}
resolver.registerContentObserver(uri, false, observer)
onDispose { resolver.unregisterContentObserver(observer) }
}
return reduce
}
private fun readScale(context: Context): Float =
Settings.Global.getFloat(context.contentResolver, Settings.Global.ANIMATOR_DURATION_SCALE, 1f)
Why
remember(anchors)is safe.rememberAnchorsreturns a holder remembered on the fiveState<Color>instances, which are stable across recompositions. The holder is therefore the same object each time, and the painter is built once instead of on every parent recomposition.
6. Performance: frame timing vs an AGSL shader version
Mesh gradients are a draw-phase effect on every frame, so cost per frame matters most on 90/120 Hz panels, where the budget shrinks to 11.1 ms and 8.3 ms respectively.
I compared three implementations of the same full-screen backdrop:
- MeshGradientPainter, 3 × 3 patches, bicubic color, 8 interior vertices drifting.
-
AGSL shader, a custom
RuntimeShaderdoing a 2 × 2 smoothstep blend of a 3 × 3 color lattice with a sinusoidal UV warp (API 33+). -
Stacked radial brushes, four
Brush.radialGradientlayers with animated centers, the classic workaround.
The AGSL version is not a visual twin. It blends four large cells with a warped lookup, rather than evaluating Bézier patches with Catmull-Rom color. That makes it a fair cost baseline but an unfair quality comparison.
private const val MESH_AGSL = """
uniform float2 uSize;
uniform float uTime;
uniform float4 uColors[9];
float4 colorAt(int idx) {
float4 result = uColors[0];
for (int k = 0; k < 9; k++) { if (k == idx) result = uColors[k]; }
return result;
}
half4 main(float2 frag) {
float2 uv = frag / uSize;
float a = uTime * 6.2831853;
uv += 0.06 * float2(sin(a + uv.y * 4.0), cos(a + uv.x * 4.0));
uv = clamp(uv, 0.0, 1.0);
float2 g = uv * 2.0;
int x = int(min(floor(g.x), 1.0));
int y = int(min(floor(g.y), 1.0));
float2 f = smoothstep(0.0, 1.0, g - float2(float(x), float(y)));
float4 top = mix(colorAt(y * 3 + x), colorAt(y * 3 + x + 1), f.x);
float4 bot = mix(colorAt((y + 1) * 3 + x), colorAt((y + 1) * 3 + x + 1), f.x);
return half4(mix(top, bot, f.y));
}
"""
Note the colorAt helper. AGSL is derived from SkSL and follows the restricted GLSL ES 1.00 subset (the ES 2.0 shading language) for runtime effects, so indexing a uniform array with a computed value is the kind of thing that fails to compile; looping over constants and comparing is the portable workaround.
@RequiresApi(33)
@Composable
fun AgslBackdrop(colors: List<Color>, modifier: Modifier = Modifier) {
require(colors.size == 9) { "AgslBackdrop needs exactly 9 colors" }
val shader = remember { RuntimeShader(MESH_AGSL) }
val clock = rememberInfiniteTransition(label = "agsl").animateFloat(
0f, 1f, infiniteRepeatable(tween(14_000, easing = LinearEasing)), label = "t",
)
val packed = remember(colors) {
FloatArray(36).also { out ->
colors.forEachIndexed { i, c ->
out[i * 4] = c.red; out[i * 4 + 1] = c.green
out[i * 4 + 2] = c.blue; out[i * 4 + 3] = c.alpha
}
}
}
Canvas(modifier) {
if (size.width <= 0f || size.height <= 0f) return@Canvas // avoid frag / 0
shader.setFloatUniform("uSize", size.width, size.height)
shader.setFloatUniform("uTime", clock.value) // draw-phase read
shader.setFloatUniform("uColors", packed)
drawRect(ShaderBrush(shader))
}
}
How to measure it
Use Macrobenchmark’s FrameTimingMetric, with a release-like build and a fixed compilation mode, and read the P50/P95/P99 of frame duration:
@RunWith(AndroidJUnit4::class)
class BackdropBenchmark {
@get:Rule val rule = MacrobenchmarkRule()
@Test fun meshPainter() = measure("painter")
@Test fun agsl() = measure("agsl")
@Test fun radialStack() = measure("radial")
private fun measure(variant: String) = rule.measureRepeated(
packageName = "com.example.lagoon",
metrics = listOf(FrameTimingMetric()),
compilationMode = CompilationMode.Partial(),
startupMode = StartupMode.WARM,
iterations = 10,
) {
pressHome()
startActivityAndWait(
Intent().setClassName(packageName, "$packageName.BackdropActivity")
.putExtra("variant", variant)
)
// Deterministic window: waitForIdle can return early or time out
// while an infinite animation is scheduling frames.
Thread.sleep(15_000)
}
}
What I would expect you to see, and why:
-
AGSL is the cheapest because it is a single fragment pass with a handful of
mixcalls. It also carries the highest maintenance cost: you own the math, the fallback for API < 33, and the compile-time failure modes. - The mesh painter sits in the middle. You pay for patch evaluation and bicubic color, and you get Bézier-shaped boundaries and an API that is state-aware and testable.
- Stacked radial brushes lose on the tail. Four full-screen alpha-blended layers mean four times the fill, and the p99 is where you feel it.
-
Frame duration is not raw GPU time.
FrameTimingMetricreportsframeDurationCpuMsandframeOverrunMs; the overrun reflects missed deadlines, so GPU delays show up there. To isolate GPU cost, capture a Perfetto trace and look at the GPU completion slices.
The practical rule: pick the mesh painter by default, move to AGSL only if a trace shows the backdrop costing real budget on your lowest-tier target.
7. Gotchas: overdraw, recomposition vs draw-phase animation
7.1 Recomposition vs draw-phase animation
This is the failure mode that turns a nice effect into a battery bug.
// Anti-pattern: `by` unwraps the State inside the composable body.
val t by infinite.animateFloat(0f, 1f, spec, label = "t")
val painter = remember(t) { MeshGradientPainter(3, 3, true) { /* uses t */ } }
Reading t in the body subscribes the composition to the animation. You recompose every frame, and with remember(t) you also rebuild the painter every frame. Layout Inspector's recomposition counts will climb at your refresh rate.
The corrected pattern is the one used throughout this post: hold the State<Float> and call .value only inside the painter block.
7.2 Overdraw
A full-screen mesh is expensive enough that you should not draw it and then cover it.
-
Opaque containers on top. A
Scaffoldwith the defaultcontainerColor, or aSurfacearound your screen content, paints an opaque rectangle over the mesh. You paid for the backdrop and nobody sees it. Set the container toColor.Transparentwhere the mesh should show, and keep real surfaces only where content needs them. -
Stacked backdrops. A mesh behind a blurred card behind another gradient is three layers of full-bounds fill. Cap the mesh to the region that is actually visible, for example the hero height rather than
fillMaxSize(). - How to see it. Turn on Debug GPU overdraw in developer options, or use the Perfetto GPU slices. In that overlay, blue is 1× overdraw and green is 2×. Blue to green across the screen is normal for this effect; light red (3×) or dark red (4×+) means you are drawing things nobody can see.
7.3 Seams and creases
- If edge vertices drift inward, you will see the window background through the gap. Pin the border, as in Build 2.
- If amplitude exceeds a fraction of the lattice spacing, interior patches fold. Cap amplitude at about a quarter of the spacing.
7.4 Color problems
- Distant stops with very different hue produce muddy midpoints. Add an intermediate stop rather than increasing
rowsandcolumns. - Bicubic color is smoother but not free. If a trace shows draw time dominating, try
hasBicubicColor = falseand compare visually before committing.
7.5 Lifecycle, accessibility, and tests
-
Gate the clock. An
InfiniteTransitionkeeps ticking while the composable is in the tree. Stop it when the lifecycle drops belowSTARTED(note this stays true when the activity is merely paused, for example in multi-window; useRESUMEDif you want to stop there too), and respect a system animator scale of zero. The helpers in Build 3 observe the setting, so toggling "Remove animations" takes effect while the app is open. -
Make previews and screenshot tests deterministic. Expose
animate: Booleanand passfalsein@Previewfunctions and screenshot tests so the frame you assert on is the frame you expect. - Contrast. A drifting backdrop changes the luminance behind your text over time. Use the scrim, or verify contrast against the lightest and darkest frames of the loop, not just the first one.
Checklist before you ship
- [ ] Vertex count matches
(rows + 1) × (columns + 1) - [ ] Border vertices pinned; amplitude ≤ spacing / 4
- [ ] Animated value read only inside the painter
block - [ ] Opaque containers above the mesh removed
- [ ] Clock gated on lifecycle and reduced motion
- [ ] Contrast verified across the whole loop
- [ ] Benchmarked on your lowest-tier device, not your daily driver
🚀 Master Android Architecture: Volume 2, Architecture at Scale
What happens when your app and your team grow? This volume takes NowReading into modularization, Gradle convention plugins, architecture for large teams and legacy migration. It then covers testing strategy, performance and security, and finishes with Kotlin Multiplatform, adaptive layouts, on-device AI and an end-to-end case study. The appendices collect all 26 ADRs, cheat sheets, a pattern comparison and a system design interview guide.
- E-book: Available on Google Play
- Kindle Edition: Available on Amazon
- Topmate: Available on Topmate
- Also available in Paperback & Hardcover.






Top comments (0)