# Introduction to Shaders

> What a shader actually is in Compose, and how to write your first one with AGSL.

**Date:** 2026-10-20T00:00:00.000Z
**Tags:** Shader, Canvas, AGSL

## What a shader actually is

A **shader** is a small program the GPU runs, not a function you call
once. For a fragment shader (A shader stage that decides the final color of one pixel, as opposed to a vertex shader, which only positions geometry. AGSL in Compose only exposes this stage.),
that program runs once *per pixel*, for every pixel inside the area
being drawn, every single frame.

**AGSL** (Android Graphics Shading Language) is Android's shader
language. It isn't a new invention: it's a constrained dialect of
SkSL (Skia's own shading language. AGSL is syntactically close to SkSL, which is itself close to GLSL ES. Learning AGSL transfers almost directly to SkSL and most of the way to GLSL.),
which is itself close to GLSL ES. You write it as a plain string,
compile it at runtime with `RuntimeShader`, and use the result as a
`Brush` or a `RenderEffect` anywhere Compose expects one.

## The intuition

It's easy to picture a shader as a filter you configure once and apply
to a whole image, the same way `BlurEffect` or `ColorMatrix` work. A
shader isn't that. It's closer to a function with no idea an image
even exists:

* The GPU invokes your shader's `main` separately for every pixel in
  the draw area, in parallel, with no guaranteed order between
  invocations.
* Each invocation only knows its own pixel coordinate and whatever
  uniform (A value you pass into a shader from Kotlin before it runs, constant for every pixel in that draw call: a color, a size, a time value, a texture. Not an input the shader can see per-pixel variation in.)
  values you handed it before the draw call. It cannot read a
  neighboring pixel, loop over the image, or remember anything from
  the pixel next to it or the frame before.
* Anything a shader "sees" beyond its own coordinate, a texture, a
  gradient, last frame's output, has to be explicitly sampled, because
  nothing is implicitly shared between invocations.

That's the whole mental shift: a shader describes *one pixel's* color
as a pure function of its coordinate and its uniforms, and the GPU is
the thing that runs that description millions of times a frame.

## A minimal AGSL shader

Here's a fragment shader that paints an animated plasma field: color
computed from each pixel's position and the current time, recombining
into bands that shift continuously. A `Brush.radialGradient` can fake a
static vignette, but nothing in `Brush` can fake this, because the
color at every pixel is a non-linear function of two inputs at once,
position and time, recomputed by the GPU every single frame. The AGSL
source is a string, no different from any other Kotlin string literal:

```kotlin
private const val PLASMA_SHADER = """
    uniform float2 resolution;
    uniform float time;

    half4 main(float2 fragCoord) {
        float2 uv = fragCoord / resolution;
        float wave = sin(uv.x * 10.0 + time) + cos(uv.y * 10.0 - time * 1.3);
        float3 color = 0.5 + 0.5 * cos(float3(wave, wave + 2.0, wave + 4.0));
        return half4(color, 1.0);
    }
"""
```

Notice what `main` actually receives: `fragCoord`, the pixel this one
invocation is responsible for, nothing else. Neither `resolution` nor
`time` is automatic, both are uniforms you're expected to set yourself,
because the shader has no built-in notion of "the size of the thing I'm
drawing into" or "how long the app has been running."

Wiring it into Compose means compiling it once with `RuntimeShader`,
keeping both uniforms up to date, `resolution` when the size changes and
`time` on every single frame, and handing the result to any API that
takes a `Brush`:

```kotlin
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    val plasmaShader = remember { RuntimeShader(PLASMA_SHADER) }
    val elapsedSeconds by produceState(0f) {
        val start = withFrameMillis { it }
        while (true) {
            withFrameMillis { value = (it - start) / 1000f }
        }
    }

    Box(
        modifier = Modifier
            .fillMaxSize()
            .onSizeChanged { size ->
                plasmaShader.setFloatUniform(
                    "resolution",
                    size.width.toFloat(),
                    size.height.toFloat(),
                )
            }
            .drawBehind {
                plasmaShader.setFloatUniform("time", elapsedSeconds)
                drawRect(brush = ShaderBrush(plasmaShader))
            },
    )
}
```

`RuntimeShader` compiles the AGSL source immediately, so a typo in the
shader string throws at construction, not at draw time. `ShaderBrush`
is what bridges it into Compose: it implements `Brush`, so anything
that paints with a `Brush` (`background`, `Canvas.drawRect`, a `Text`
color) can paint with a shader instead of a flat color or gradient.

[Video](/posts/intro-to-shaders/plasma-shader.webm)

*Animated plasma shader filling a Box: color bands shifting continuously from sin/cos of position and time, something no static Brush gradient can reproduce.*

> **The fundamental**
>
> A shader is a **data-parallel, stateless, per-pixel program**. "Data-
> parallel" means the same program runs independently across many pixels
> at once instead of looping over them one at a time. "Stateless" means
> each invocation starts fresh: no memory of other pixels, no memory of
> the last frame, unless you explicitly feed it back in as a uniform or a
> sampled texture.

## Where this shows up in real apps

The plasma field above is deliberately a toy. The same per-pixel model
is what's actually running behind effects you've already seen shipped:

* **Frosted-glass / blur-behind dialogs**: the shader samples a
  snapshot of whatever's behind it and blurs per pixel, which is how
  Android 12+'s dialog and notification-shade blur works under
  `RenderEffect`.
* **Color grading and LUT filters**: each pixel's RGB is remapped
  through a lookup function, the same idea Instagram- or Lightroom-style
  filters use, just expressed as AGSL math instead of a fixed
  `ColorMatrix`.
* **Touch ripple and distortion feedback**: the shader samples its own
  content shader at an offset computed from distance-to-touch and
  elapsed time, producing a water-ripple "squish" as the finger moves,
  the same family of effect behind custom pull-to-refresh and liquid
  swipe interactions (not Android's built-in `RippleDrawable`, which is
  a plain circular alpha reveal with no shader involved).
* **Procedural textures and grain**: backgrounds, noise, and dither
  patterns generated from pure math at draw time, like this post's
  plasma field, instead of shipping a bitmap asset that has to scale
  and tile.
* **Chromatic aberration and glitch effects**: the red, green, and blue
  channels are sampled at slightly different coordinate offsets, a
  common stylistic effect in camera and photo-editing apps.

Every one of these is the same mental model from this post applied to a
different per-pixel function: only the math inside `main` changes.

## Elsewhere: same fundamental, different framework

* **GLSL (OpenGL/WebGL)**: the shading language AGSL and SkSL both
  descend from. A WebGL fragment shader's `void main()` writing to
  `gl_FragColor` is the exact same per-pixel, stateless model, just
  with OpenGL's binding conventions instead of `RuntimeShader`'s.
* **HLSL (Direct3D, Unity)**: same per-pixel entry point, different
  syntax and binding model. A Unity fragment shader's `frag` function
  receives interpolated per-pixel data and returns a color exactly the
  way AGSL's `main` does.
* **Metal Shading Language (iOS/macOS)**: a `fragment` function
  annotated function that runs once per pixel/fragment, reading
  explicit arguments for anything it needs, no implicit access to
  neighboring output.
* **SkSL (Skia)**: not just an analog, AGSL's actual parent. Skia uses
  SkSL internally for its own effects, and AGSL is the public, slightly
  restricted subset of it exposed to app code.

## Where this actually trips people up

* **It crashes at runtime below API 33, not at compile time.**
  `RuntimeShader` requires Android 13 (Tiramisu). There's no compile
  warning for calling it on an older `minSdk`, the crash only happens
  the first time that code path executes, so the
  `Build.VERSION.SDK_INT` check isn't optional boilerplate, it's
  load-bearing.
* **The shader compiles but the output is black or fully transparent.**
  The most common cause is an untouched uniform: `resolution` defaults
  to `(0, 0)` until you call `setFloatUniform`, so `fragCoord /
  resolution` divides by zero on the very first frame if you set it
  after the first draw instead of before.
* **AGSL defaults to full `float` precision, not GLSL ES's `mediump`.**
  Porting a GLSL ES fragment shader that relies on `mediump float`'s
  narrower range for an intentional banding or wraparound effect won't
  reproduce the same artifact in AGSL unless you account for the wider
  default precision explicitly.

## Mental model to actually use

Stop asking "what does this shader see." Ask instead: **"what does this
one pixel know?"** A shader never sees the image, the screen, or the
previous frame, it only ever sees its own coordinate and whatever
uniforms you remembered to set, which is also exactly why it can run a
million times a frame without stepping on itself.


---

Canonical page: https://recomposed.blog/intro-to-shaders