Interactive Dotted Background

In this article you'll build an interactive dotted background shader in SwiftUI. The dots react to a finger or mouse pointer: they glow, push away, or pull in, depending on how close they are. I'll build it one step at a time and explain each line, with an interactive visualization before each new idea.

What we'll cover

  • UV normalization: dividing by the view size so the math works at any screen size.
  • Signed distance functions (SDFs): describing a shape as a distance from each pixel.
  • smoothstep: turning a distance into a soft 0 to 1 mask, which gives antialiased edges.
  • fract: repeating a coordinate space into tiles.
  • floor: finding which tile a pixel belongs to.
  • Uniforms: values you pass from Swift that are the same for every pixel.
  • mix: linear interpolation between two values.
  • normalize: getting a direction out of a vector.
  • Moving a shape by moving its center before the distance test, which is how repulsion and attraction work.

What we're building

A grid of dots drawn entirely on the GPU. Each dot reacts to the position of your finger or cursor, in one of three modes: glow, repulsion, or attraction. Try them here:

Final result — dotted background

Move your cursor or touch to interact

mode

Step 0: the shader signature

Before drawing anything, here is the function signature every step uses:

[[stitchable]]
half4 step0_black(float2 position, half4 color,
                  float2 size,       // canvas size in points
                  float2 touch,      // touch position in points
                  float mode,        // 0=glow, 1=attraction, 2=repulsion
                  float intensity)   // 0=idle, 1=active (animated from Swift)
{
    return half4(0.0, 0.0, 0.0, 1.0);
}

Three things to notice.

[[stitchable]] is a Metal attribute that marks the function so it can be linked into other shader code at runtime. SwiftUI needs it to plug your function into its rendering. Without it the file still compiles, but SwiftUI can't load the function at runtime and the effect doesn't draw.

float2 position, half4 color are filled in by SwiftUI for every pixel. You never pass them from Swift. position is the pixel's location in the view's own coordinate space, measured in points, with (0, 0) at the top left and y growing downward. color is the color the view already has at that position. Here the view is Color.black, so color is always black, and none of the steps use it.

Everything after those two is yours. size, touch, mode and intensity come from the Swift call, in the same order. Metal matches arguments by position, not by name, so if you swap two .float() arguments in Swift, the shader silently gets the wrong values.

On the Swift side:

Color.black
    .visualEffect { content, geo in
        content.colorEffect(
            ShaderLibrary.step0_black(
                .float2(geo.size.width, geo.size.height),
                .float2(0, 0),
                .float(0),  // mode
                .float(0)   // intensity
            )
        )
    }

colorEffect doesn't tell the shader how big the view is. You have to pass the size yourself, and visualEffect is the easiest place to get it: its closure receives a geometry proxy (geo) with the view's size, so the size is always current, even when the view resizes.

Step 0: black canvas

Just proving the shader is wired up. Returns solid black.

[[stitchable]]
half4 step0_black(float2 position, half4 color,
                float2 size,
                float2 touch,
                float mode)
{
  return half4(0.0, 0.0, 0.0, 1.0);
}
SwiftUI Metal Shader

Step 1: drawing a circle with an SDF

A shader has no "draw circle here" call. It runs once for every pixel, and each run answers one question: what color is this pixel? To draw a circle, each pixel asks whether it is inside the circle or outside.

A signed distance function answers that with a number:

dist = radius - length(uv - center)

length(uv - center) is how far the pixel is from the circle's center. Subtracting that from the radius gives:

  • a positive value inside the circle,
  • zero exactly on the edge,
  • a negative value outside.

Most SDF code you'll find elsewhere uses the opposite sign (negative inside). I've flipped it here so that "inside" is the larger value, which makes the next step read more naturally.

float dist = radius - length(uv - center)// + inside, − outside
radius0.25
move cursor over the canvas
dist = -0.0163 → ✗ outside circle (negative)

Next, turn that distance into a mask between 0 and 1 with smoothstep:

float circle = smoothstep(-eps, eps, dist);

smoothstep(-eps, eps, dist) returns 0 when dist is at or below -eps (outside), 1 when it's at or above eps (inside), and a smooth S-curve in between. That in-between band is the antialiased edge. Without it, every pixel would be either fully on or fully off, and the circle's edge would look jagged.

smoothstep(-a, +b, dist)// dist = radius - length(uv - center)
a-0.020
b+0.020
← outside (dist negative)circle edge (dist=0)inside (dist positive) →
dist0.010→0.844
dist (0.010) is in the antialiased edge zone → result = 0.844

The full step 1 shader:

[[stitchable]]
half4 step1_circle(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float2 center = float2(0.5, 0.5);
    float radius = 0.05;

    float dist = radius - length(uv - center);
    float circle = smoothstep(-0.005, 0.005, dist);

    return half4(half3(circle), 1.0);
}

Why divide position by size? Position arrives in points, from 0 to the view's width (400 on a 400-point canvas). Dividing by the size maps both axes to 0 to 1, called UV space. A center of (0.5, 0.5) is then the middle of the view at any size.

How wide is the soft edge? With eps = 0.005, the blend runs from -0.005 to 0.005, a band 0.01 UV units wide. On a 400-point canvas that's 4 points. Lower eps for a crisper edge.

Why might the circle look oval? UV space stretches to fill the rectangle. On a 400 × 200 view, 0.1 UV units across is 40 points but 0.1 UV units down is only 20 points. Correct for that before calling length():

float2 delta = (uv - center) * float2(size.x / size.y, 1.0);
float dist = radius - length(delta);

Multiplying x by size.x / size.y (2 on the 400 × 200 view) makes one unit mean the same distance on both axes.

Step 1: SDF circle

A single circle at the center of the canvas using a Signed Distance Field.

[[stitchable]]
half4 step1_circle(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float2 center = float2(0.5, 0.5);
  float radius = 0.05;

  float dist = radius - length(uv - center);
  float circle = smoothstep(-0.005, 0.005, dist);

  return half4(half3(circle), 1.0);
}
SwiftUI Metal Shader

Step 2: tiling with fract()

One dot works. Now we need a grid of them (20 × 20 on a square canvas, so 400 dots). The tool for that is fract().

fract(x) returns the fractional part of x, everything after the decimal point:

fract(0.7)  = 0.7
fract(1.7)  = 0.7   // strips the 1
fract(3.7)  = 0.7   // strips the 3

The result is always at least 0 and less than 1, and it repeats. Multiply UV by N and take fract, and you get N tiles, each with its own coordinates running from 0 to 1.

float2 cellUV = fract(uv.x * cols)
uv.x0.370
cols5
uv.x * cols
1.850
floor(...)
1
fract(...)
0.850
dot centre
0.300
pixel at uv.x=0.370 → scaled to 1.850 → cell 1 → fract = 0.850 → dot centre (1+0.5)/5 = 0.300
float2 cellUV = fract(uv * float2(cols, rows));

cellUV now runs from (0, 0) to (1, 1) inside every cell. Take a pixel at position (130, 50) on a 400 × 400 canvas with 20 columns and rows:

  • uv = (130, 50) / 400 = (0.325, 0.125)
  • uv * 20 = (6.5, 2.5)
  • fract((6.5, 2.5)) = (0.5, 0.5), the exact center of its cell.

Because every cell has the same local coordinates, the same circle test at (0.5, 0.5) draws a dot in every cell at once.

[[stitchable]]
half4 step2_grid(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float cols = 20.0;
    float rows = cols * (size.y / size.x);  // keep cells square

    float2 cellUV = fract(uv * float2(cols, rows));
    float radius = 0.15;
    float dist = radius - length(cellUV - 0.5);
    float dot_ = smoothstep(-0.02, 0.02, dist);

    return half4(half3(dot_), 1.0);
}

Why cols * (size.y / size.x) for rows? Each cell is size.x / cols points wide and size.y / rows points tall. Using 20 for both would only give square cells on a square canvas. On a 400 × 800 view, 20 columns makes cells 20 points wide, and rows = 20 * 2 = 40 makes them 800 / 40 = 20 points tall.

The variable is called dot_ because dot is already a Metal function (the dot product).

Step 2: dot grid

fract() tiles the SDF circle across the whole canvas.

[[stitchable]]
half4 step2_grid(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float cols = 20.0;
  float rows = cols * (size.y / size.x);

  float2 cellUV = fract(uv * float2(cols, rows));
  float radius = 0.15;
  float dist = radius - length(cellUV - 0.5);
  float dot_ = smoothstep(-0.02, 0.02, dist);

  return half4(half3(dot_), 1.0);
}
SwiftUI Metal Shader

Step 3: the touch uniform

The grid doesn't move yet. Next we pass the touch position from Swift. Values like this are called uniforms: Swift sends one value per frame, and every pixel sees the same value.

ShaderLibrary.step3_touch(
    .float2(geo.size.width, geo.size.height),
    .float2(touchPosition.x, touchPosition.y),  // ← live position
    .float(0)
)

To check that the value arrives correctly, this step draws a small blue indicator at the touch position on top of the grid:

[[stitchable]]
half4 step3_touch(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float cols = 20.0;
    float rows = cols * (size.y / size.x);

    // Dot grid, same as step 2
    float2 cellUV = fract(uv * float2(cols, rows));
    float dotRadius = 0.15;
    float dotMask = smoothstep(-0.02, 0.02, dotRadius - length(cellUV - 0.5));

    // Touch indicator
    float2 touchUV = touch / size;
    float indicatorRadius = 0.03;
    float indicator = smoothstep(-0.02, 0.02, indicatorRadius - length(uv - touchUV));

    half3 c = half3(dotMask) + half3(0.0, 0.5, 1.0) * indicator;
    return half4(c, 1.0);
}

touch comes from a DragGesture location, which is in the same coordinate space as position: points, origin at the top left of the view. Dividing it by size puts it in UV space so you can compare it with uv.

Step 3: touch indicator

The blue dot orbits automatically in this preview. On device it follows your touch.

[[stitchable]]
half4 step3_touch(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float cols = 20.0;
  float rows = cols * (size.y / size.x);

  float2 cellUV = fract(uv * float2(cols, rows));
  float dotRadius = 0.15;
  float dotMask = smoothstep(-0.02, 0.02, dotRadius - length(cellUV - 0.5));

  float2 touchUV = touch / size;
  float indicatorRadius = 0.03;
  float indicator = smoothstep(-0.02, 0.02, indicatorRadius - length(uv - touchUV));

  half3 c = half3(dotMask) + half3(0.0, 0.5, 1.0) * indicator;
  return half4(c, 1.0);
}
SwiftUI Metal Shader

Step 4: glow

Now the dots react. Dots near the touch should grow and brighten.

To decide how much a dot reacts, we need the distance from that dot to the touch. fract() only tells a pixel where it is inside its cell. It doesn't say where the cell is on the canvas. floor() does:

float2 scaled = uv * float2(cols, rows);
float2 cellIndex = floor(scaled);              // which cell: (0,0), (1,0), (2,0)...
float2 dotWorld = (cellIndex + 0.5) / float2(cols, rows);  // dot center in UV space

floor() drops the fractional part, leaving the cell's column and row. Adding 0.5 moves to the middle of that cell, and dividing by the grid size converts back to UV space. For the pixel from step 2, scaled is (6.5, 2.5), so cellIndex is (6, 2) and dotWorld is (6.5, 2.5) / 20 = (0.325, 0.125). Every pixel in that cell computes the same dotWorld, so the whole dot reacts as one.

float2 cellIndex = floor(uv * cols)// which cell?
uv.x0.37
uv.y0.55
cols5
cellIndex
(1, 2)
dotWorld
(0.30, 0.50)
length(dotWorld - pixel)
0.0860
pixel → cell (1,2) → dot centre (0.300, 0.500) → distance = 0.0860

With the dot's position, measure its distance to the touch and turn that into an influence value:

float touchDist = length(dotWorld - touchUV);
float influenceRadius = 0.2;
float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);
// influence = 1 at the touch, smoothly fades to 0 beyond influenceRadius

Then use influence to set the radius and brightness:

float radius = mix(minRadius, maxRadius, influence);
float brightness = mix(0.25, 1.0, influence);

mix(a, b, t) is linear interpolation: it returns a when t is 0, b when t is 1, and the matching point in between otherwise. A dot 0.1 UV units from the touch is halfway through the influence radius, so smoothstep returns 0.5 and influence is 0.5. Its radius is mix(0.12, 0.22, 0.5) = 0.17 and its brightness is mix(0.25, 1.0, 0.5) = 0.625.

[[stitchable]]
half4 step4_glow(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float cols = 20.0;
    float rows = cols * (size.y / size.x);

    float2 scaled = uv * float2(cols, rows);
    float2 cellIndex = floor(scaled);
    float2 dotWorld = (cellIndex + 0.5) / float2(cols, rows);

    float2 touchUV = touch / size;
    float touchDist = length(dotWorld - touchUV);
    float influenceRadius = 0.2;
    float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);

    float2 cellUV = fract(scaled);
    float minRadius = 0.12;
    float maxRadius = 0.22;
    float radius = mix(minRadius, maxRadius, influence);
    float dist = radius - length(cellUV - 0.5);
    float dotMask = smoothstep(-0.02, 0.02, dist);

    float brightness = mix(0.25, 1.0, influence);
    return half4(half3(brightness * dotMask), 1.0);
}

Step 4: glow

Dots grow and brighten near the touch. The touch orbits automatically in this preview.

[[stitchable]]
half4 step4_glow(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float cols = 20.0;
  float rows = cols * (size.y / size.x);

  float2 scaled = uv * float2(cols, rows);
  float2 cellIndex = floor(scaled);
  float2 dotWorld = (cellIndex + 0.5) / float2(cols, rows);

  float2 touchUV = touch / size;
  float touchDist = length(dotWorld - touchUV);
  float influenceRadius = 0.2;
  float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);

  float2 cellUV = fract(scaled);
  float minRadius = 0.12;
  float maxRadius = 0.22;
  float radius = mix(minRadius, maxRadius, influence);
  float dist = radius - length(cellUV - 0.5);
  float dotMask = smoothstep(-0.02, 0.02, dist);

  float brightness = mix(0.25, 1.0, influence);
  return half4(half3(brightness * dotMask), 1.0);
}
SwiftUI Metal Shader

Step 5: repulsion

Now the dots should move away from the touch. In a shader there is no dot object to move. A dot is just the set of pixels that pass the "am I inside the circle?" test. To make it appear somewhere else, move the center that the test measures against.

So far the center was implicit: length(cellUV - 0.5) measures from the middle of the cell. This step works in scaled grid space instead, where the middle of cell (6, 2) is cellIndex + 0.5 = (6.5, 2.5). We push that center along the direction from the touch to the dot, then run the circle test against the moved center:

float2 awayDir = dotWorld - touchUV;  // direction: touch → dot
float2 dir = normalize(awayDir);

// Shift dot center AWAY from touch → dot appears to have moved away
dotCenter += dir * (influence * maxDisplacement);

awayDir points from the touch to the dot. normalize scales it to length 1, so dir is only a direction, and the distance moved comes entirely from influence * maxDisplacement. With maxDisplacement = 0.4, a dot right next to the touch moves 0.4 of a cell away, and dots outside the influence radius don't move.

[[stitchable]]
half4 step5_repulsion(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float cols = 20.0;
    float rows = cols * (size.y / size.x);
    float2 grid = float2(cols, rows);

    float2 scaled = uv * grid;
    float2 cellIndex = floor(scaled);
    float2 dotWorld = (cellIndex + 0.5) / grid;

    float2 touchUV = touch / size;
    float2 awayDir = dotWorld - touchUV;
    float touchDist = length(awayDir);
    float2 dir = touchDist > 0.001 ? normalize(awayDir) : float2(0.0);
    float influenceRadius = 0.2;
    float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);
    float maxDisplacement = 0.4;

    float2 dotCenter = cellIndex + 0.5;
    dotCenter += dir * (influence * maxDisplacement);  // push away

    float radius = 0.12;
    float dist = radius - length(scaled - dotCenter);
    float dotMask = smoothstep(-0.02, 0.02, dist);

    float brightness = mix(0.25, 1.0, 1.0 - influence);
    return half4(half3(brightness * dotMask), 1.0);
}

Why check touchDist > 0.001 before normalize? normalize divides a vector by its length. When the touch sits exactly on a dot's center, the length is 0, and the division produces NaN (not a number), which renders as garbage. The guard uses a zero direction in that case, so that dot simply doesn't move.

Brightness is reversed compared with glow: mix(0.25, 1.0, 1.0 - influence) dims the dots closest to the touch, which makes the cleared area around your finger easier to see.

The browser previews on this page take a different route to the same result: instead of moving the dot's center, they move the sample coordinate (cellUV) in the opposite direction. Moving the point you measure from toward the touch looks the same as moving the dot away from it. That's why you'll see the opposite sign if you read the preview source.

Step 5: repulsion

Dots push away from the touch. We shift the dot center, not the sample coordinate.

[[stitchable]]
half4 step5_repulsion(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float cols = 20.0;
  float rows = cols * (size.y / size.x);
  float2 grid = float2(cols, rows);

  float2 scaled = uv * grid;
  float2 cellIndex = floor(scaled);
  float2 dotWorld = (cellIndex + 0.5) / grid;

  float2 touchUV = touch / size;
  float2 awayDir = dotWorld - touchUV;
  float touchDist = length(awayDir);
  float2 dir = touchDist > 0.001 ? normalize(awayDir) : float2(0.0);
  float influenceRadius = 0.2;
  float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);
  float maxDisplacement = 0.4;

  float2 dotCenter = cellIndex + 0.5;
  dotCenter += dir * (influence * maxDisplacement);

  float radius = 0.12;
  float dist = radius - length(scaled - dotCenter);
  float dotMask = smoothstep(-0.02, 0.02, dist);

  float brightness = mix(0.25, 1.0, 1.0 - influence);
  return half4(half3(brightness * dotMask), 1.0);
}
SwiftUI Metal Shader

Step 6: attraction

Attraction is repulsion with the sign flipped. Subtracting dir moves the center toward the touch instead of away from it:

// Repulsion: shift dot center AWAY from touch
dotCenter += dir * (influence * maxDisplacement);

// Attraction: shift dot center TOWARD touch
dotCenter -= dir * (influence * maxDisplacement);

The brightness goes back to the glow version, so dots get brighter as they gather around the touch:

[[stitchable]]
half4 step6_attraction(float2 position, half4 color, float2 size, float2 touch, float mode)
{
    float2 uv = position / size;
    float cols = 20.0;
    float rows = cols * (size.y / size.x);
    float2 grid = float2(cols, rows);

    float2 scaled = uv * grid;
    float2 cellIndex = floor(scaled);
    float2 dotWorld = (cellIndex + 0.5) / grid;

    float2 touchUV = touch / size;
    float2 awayDir = dotWorld - touchUV;
    float touchDist = length(awayDir);
    float2 dir = touchDist > 0.001 ? normalize(awayDir) : float2(0.0);
    float influenceRadius = 0.2;
    float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);
    float maxDisplacement = 0.4;

    float2 dotCenter = cellIndex + 0.5;
    dotCenter -= dir * (influence * maxDisplacement);  // ← flipped

    float radius = 0.12;
    float dist = radius - length(scaled - dotCenter);
    float dotMask = smoothstep(-0.02, 0.02, dist);

    float brightness = mix(0.25, 1.0, influence);
    return half4(half3(brightness * dotMask), 1.0);
}

Step 6: attraction

One sign flip from repulsion. Dots collapse toward the touch.

[[stitchable]]
half4 step6_attraction(float2 position, half4 color, float2 size, float2 touch, float mode)
{
  float2 uv = position / size;
  float cols = 20.0;
  float rows = cols * (size.y / size.x);
  float2 grid = float2(cols, rows);

  float2 scaled = uv * grid;
  float2 cellIndex = floor(scaled);
  float2 dotWorld = (cellIndex + 0.5) / grid;

  float2 touchUV = touch / size;
  float2 awayDir = dotWorld - touchUV;
  float touchDist = length(awayDir);
  float2 dir = touchDist > 0.001 ? normalize(awayDir) : float2(0.0);
  float influenceRadius = 0.2;
  float influence = 1.0 - smoothstep(0.0, influenceRadius, touchDist);
  float maxDisplacement = 0.4;

  float2 dotCenter = cellIndex + 0.5;
  dotCenter -= dir * (influence * maxDisplacement);

  float radius = 0.12;
  float dist = radius - length(scaled - dotCenter);
  float dotMask = smoothstep(-0.02, 0.02, dist);

  float brightness = mix(0.25, 1.0, influence);
  return half4(half3(brightness * dotMask), 1.0);
}
SwiftUI Metal Shader

Putting it all together

The step shaders have one flaw. Each pixel only tests the dot of its own cell. That's fine for glow, where dots stay put. With repulsion and attraction, a dot can move partly into a neighboring cell, and the pixels there never test it, so the dot gets sliced off at the cell boundary.

The fix is for every pixel to test the dots of its own cell and the eight cells around it, a 3 × 3 neighborhood. If a neighbor's dot has moved into this pixel's cell, the pixel still finds it. Of the nine results, the pixel keeps the brightest. Since maxDisplacement plus the dot radius stays under one cell, a dot can never move further than the next cell over, so nine cells are enough.

The final version adds two more things:

  • An intensity uniform, 1 while touching and 0 when idle. It multiplies influence, so when nobody is touching the screen every dot goes back to its resting state.
  • An aspect-corrected touch distance. UV units are wider than they are tall on a non-square canvas (step 1 again), so length(float2(awayDir.x, awayDir.y * aspect)) measures the distance in units of the view's width on both axes. That keeps the area of influence circular.

It also uses 40 columns instead of 20, and a larger influence radius and displacement. Modes use the same numbering as step 0: 0 is glow, 1 attraction, 2 repulsion.

[[stitchable]]
half4 dottedBackground(float2 position, half4 color,
                       float2 size,
                       float2 touch,
                       float mode,
                       float intensity)
{
    float2 uv = position / size;
    float cols = 40.0;
    float rows = cols * (size.y / size.x);
    float2 grid = float2(cols, rows);

    float2 scaled = uv * grid;
    float2 currentCell = floor(scaled);

    float2 touchUV = touch / size;
    float aspect = size.y / size.x;
    float influenceRadius = 0.4;
    float maxDisplacement = 0.6;

    float bestBrightness = 0.0;
    float bestDotMask = 0.0;

    for (int dy = -1; dy <= 1; dy++) {
        for (int dx = -1; dx <= 1; dx++) {
            float2 neighbor = currentCell + float2(dx, dy);
            float2 dotWorld = (neighbor + 0.5) / grid;

            float2 awayDir = dotWorld - touchUV;
            float touchDist = length(float2(awayDir.x, awayDir.y * aspect));
            float2 dir = touchDist > 0.001 ? normalize(awayDir) : float2(0.0);
            float influence = (1.0 - smoothstep(0.0, influenceRadius, touchDist)) * intensity;

            float2 dotCenter = neighbor + 0.5;
            float radius = 0.12;
            float brightness = 0.25;

            if (mode < 0.5) {
                // Glow
                radius = mix(0.12, 0.22, influence);
                brightness = mix(0.25, 1.0, influence);
            } else if (mode < 1.5) {
                // Attraction
                dotCenter -= dir * (influence * maxDisplacement);
                brightness = mix(0.25, 1.0, influence);
            } else {
                // Repulsion
                dotCenter += dir * (influence * maxDisplacement);
                brightness = mix(0.25, 1.0, 1.0 - influence);
            }

            float dist = radius - length(scaled - dotCenter);
            float dotMask = smoothstep(-0.02, 0.02, dist);

            if (dotMask * brightness > bestDotMask * bestBrightness) {
                bestDotMask = dotMask;
                bestBrightness = brightness;
            }
        }
    }

    return half4(half3(bestBrightness * bestDotMask), 1.0);
}

The mode checks compare against 0.5 and 1.5 instead of testing mode == 1.0. The value arrives as a float, and comparing with a threshold halfway between the modes works even if it isn't exactly a whole number. Every pixel takes the same branch because mode is a uniform, so the if costs almost nothing.

On the Swift side, a DragGesture sets the touch position and the intensity:

Color.black
    .modifier(DottedBackgroundEffect(touch: touchPosition, mode: mode, intensity: intensity))
    .gesture(
        DragGesture(minimumDistance: 0)
            .onChanged { touchPosition = $0.location; withAnimation(.easeOut(duration: 0.15)) { intensity = 1 } }
            .onEnded { _ in withAnimation(.easeOut(duration: 0.5)) { intensity = 0 } }
    )

The shader call lives in a small view modifier:

struct DottedBackgroundEffect: ViewModifier, Animatable {
    var touch: CGPoint
    var mode: DotMode
    var intensity: CGFloat

    var animatableData: CGFloat {
        get { intensity }
        set { intensity = newValue }
    }

    func body(content: Content) -> some View {
        content.visualEffect { [touch, mode, intensity] content, geo in
            content.colorEffect(
                ShaderLibrary.dottedBackground(
                    .float2(geo.size.width, geo.size.height),
                    .float2(touch.x, touch.y),
                    .float(Float(mode.rawValue)),
                    .float(Float(intensity))
                )
            )
        }
    }
}

The modifier is there because withAnimation can't fade a shader argument by itself. SwiftUI doesn't interpolate shader arguments, so if the shader call sat directly in the view, it would receive 1 or 0 straight away and the effect would switch on and off in a single frame. A modifier that conforms to Animatable exposes intensity as its animatableData, and SwiftUI calls it with each in-between value while the animation runs. Appendix A uses the same pattern for a touch effect (TouchResponseEffect).

The capture list [touch, mode, intensity] copies the current values into the visualEffect closure. The closure is @Sendable, so with strict concurrency checking it has to capture copies rather than read properties through self.