Time-Based Animation

Animation is a number that changes

Every shader so far has been a still image. Give it the same inputs and it draws the same picture. To make it move, you add one more input, a number of seconds, and let your math depend on it. When that number grows from frame to frame, the picture changes from frame to frame, and you see motion.

That's the whole idea of this chapter. Most of the work is in two places: getting a clean, accurate time value from SwiftUI into the shader, and choosing functions of time (sine waves, fract ramps, easing curves) that look good. The effects you'll build are small. A sine wave that breathes, colors that drift, a blob that wobbles, particles on looping paths.

How time reaches the shader

A shader has no clock. There's no time built into Metal or into SwiftUI's shader effects. The time you see in the examples below is an ordinary float parameter, exactly like size. You compute it in Swift and pass it with .float(...).

What makes it animate is that SwiftUI redraws the view many times per second, and each redraw you hand the shader a slightly bigger number:

frame 1:  Swift computes t = 1.000  →  .float(t)  →  GPU runs the shader for every pixel with time = 1.000
frame 2:  Swift computes t = 1.017  →  .float(t)  →  GPU runs the shader for every pixel with time = 1.017
frame 3:  Swift computes t = 1.033  →  .float(t)  →  GPU runs the shader for every pixel with time = 1.033

Inside one frame, every pixel sees the same time. Between frames, the value changes and the whole image is recomputed. So you need two things on the Swift side: something that triggers a redraw every frame, and a time value that's correct when it does. The first is the job of TimelineView (or a timer). The second needs a little care, because of how Float works.

Why you pass elapsed time, not the current date

The obvious way to get "the time" in Swift is Date().timeIntervalSinceReferenceDate. It counts seconds since 1 January 2001, so today it's around 800 million. That's a Double in Swift, which is fine. The problem starts when you convert it with Float(...) to pass it to the shader.

A Float has 24 bits of precision. That's enough for about 7 significant digits, no matter how big the number is. Large numbers spend those digits on the part before the decimal point, so the gap between one representable Float and the next grows with the size of the number:

value of time    what it is                gap between neighboring Floats
-------------    ----------------------    -------------------------------
10               10 seconds after start    about 0.000001 s
3,600            1 hour after start        about 0.00024 s
86,400           1 day after start         about 0.0078 s
800,000,000      seconds since 2001        64 s

Look at the last row. At 800 million, the nearest Float values are 64 seconds apart. Your 60 frames per second add 0.017 s each, the conversion rounds every one of them back to the same Float, and the shader receives the same time for about a minute. Then it jumps by 64 seconds at once. The animation freezes and lurches.

The fix is to keep the number small. Record a start date once and pass the seconds since then:

@State private var startDate = Date()

// each frame
let time = Float(date.timeIntervalSince(startDate))   // 0, 0.017, 0.033, ...

Subtract in Double first, then convert. An elapsed time of a few hours still has sub-millisecond resolution, which is plenty. Store the start date in @State so it survives SwiftUI recreating your view struct; a plain let startDate = Date() gets a new value every time the parent rebuilds the view, and your animation restarts from zero.

If an effect runs for a very long time (a background that's on screen all day), you can also wrap time before converting it. If your animation repeats exactly every 10 seconds, pass elapsed.truncatingRemainder(dividingBy: 10). The shader then never sees anything bigger than 10, and because the pattern repeats on that period, the wrap is invisible.

One more precision note: keep time as float inside the shader. half has only 11 bits of precision. At time = 100, neighboring half values are 0.0625 s apart, so a half time would visibly step after under two minutes. half is great for colors, not for time or positions.

Driving time from SwiftUI

You have three ways to redraw every frame and one way that looks like it should work but doesn't. Here they are, from the one I'd reach for first.

Option 1: TimelineView

TimelineView re-runs its content closure on a schedule and hands you the date for that update. With the .animation schedule, it updates in step with the display, as often as the screen refreshes.

struct TimelineAnimationView: View {
    @State private var startDate = Date()

    var body: some View {
        TimelineView(.animation) { timeline in
            Rectangle()
                .visualEffect { content, proxy in
                    content.colorEffect(ShaderLibrary.breathingGradient(
                        .float2(proxy.size),
                        .float(Float(timeline.date.timeIntervalSince(startDate)))
                    ))
                }
        }
    }
}

timeline.date is the date of the current update. Subtracting startDate gives you the elapsed seconds, as above. If you want to pause, or limit how often it redraws, use .animation(minimumInterval:paused:). For example, TimelineView(.animation(minimumInterval: 1.0 / 30.0, paused: !isPlaying)) redraws at most 30 times a second and stops completely while isPlaying is false.

This is the default choice: no timers to manage, nothing to clean up, and it matches the display's refresh rate.

Option 2: Timer

struct TimerAnimationView: View {
    @State private var timeValue: Float = 0.0
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        Rectangle()
            .visualEffect { content, proxy in
                content.colorEffect(ShaderLibrary.breathingGradient(
                    .float2(proxy.size),
                    .float(timeValue)
                ))
            }
            .onReceive(timer) { _ in
                timeValue += 1/60.0
            }
    }
}

A Timer fires on the main run loop about 60 times a second. Each tick changes @State, which makes SwiftUI redraw. It's easy to read, and the challenge templates later in this chapter use exactly this pattern.

It has two weaknesses. It's capped at the rate you ask for, so a 120 Hz display still gets 60 updates. And this version counts ticks, not seconds: it assumes every tick is exactly 1/60 s apart. If the main thread is busy and a tick arrives late, timeValue still only grows by 1/60, so the animation runs slow. The section on frame rate independence below shows the one-line fix.

class DisplayLinkAnimator: ObservableObject {
    @Published var timeValue: Float = 0.0
    
    private var displayLink: CADisplayLink?
    private var startTime: CFTimeInterval?
    
    func start() {
        displayLink = CADisplayLink(target: self, selector: #selector(update))
        displayLink?.add(to: .main, forMode: .default)
    }
    
    func stop() {
        displayLink?.invalidate()
        displayLink = nil
    }
    
    @objc private func update(_ displayLink: CADisplayLink) {
        if startTime == nil {
            startTime = displayLink.timestamp
        }
        
        // Calculate elapsed time
        let elapsed = displayLink.timestamp - startTime!
        timeValue = Float(elapsed)
    }
}

CADisplayLink is the UIKit-level tool underneath display-synced animation. It calls you once per screen refresh and gives you a timestamp, and this class turns that into elapsed seconds. Notice it already follows the rule from earlier: it subtracts the first timestamp before converting to Float. You'd hold it in a view with @StateObject, call start() in onAppear and stop() in onDisappear, and pass .float(animator.timeValue) to the shader. In new code you'd write the class with @Observable instead of ObservableObject. The CADisplayLink(target:selector:) initializer is not available on macOS.

For shader animation in SwiftUI, TimelineView(.animation) already gives you display-synced updates, so you rarely need this. Reach for it when you need what the display link exposes, such as its frame timing properties, or when the same clock drives non-SwiftUI work.

What about withAnimation?

It's tempting to write this:

@State private var progress: Float = 0

// ...
.colorEffect(ShaderLibrary.someShader(.float(progress)))

// ...
withAnimation(.easeInOut(duration: 2)) { progress = 1 }

and expect the shader to sweep smoothly from 0 to 1. It doesn't. The view redraws once with progress = 1 and the shader jumps there. SwiftUI only interpolates values it knows how to animate, and a shader argument isn't one of them.

To make it work, wrap the shader in a view modifier that conforms to Animatable. SwiftUI then calls the modifier on every frame of the animation with an in-between value:

struct ShaderTimeModifier: ViewModifier, Animatable {
    var time: Float

    // SwiftUI writes interpolated values here on every frame of an animation
    var animatableData: Float {
        get { time }
        set { time = newValue }
    }

    func body(content: Content) -> some View {
        content.visualEffect { content, proxy in
            content.colorEffect(ShaderLibrary.breathingGradient(
                .float2(proxy.size),
                .float(time)
            ))
        }
    }
}

// Usage
Rectangle()
    .modifier(ShaderTimeModifier(time: time))
    .onTapGesture {
        withAnimation(.easeInOut(duration: 2)) { time += 3 }
    }

This is the right tool for one-off transitions with a start and an end, like a reveal that goes from 0 to 1 when the user taps. For effects that run continuously, TimelineView is simpler.

What the course app's canvas does

In the Xcode project, Chapter 9's examples use AnimatedMetalCanvasView from Utils/Utils.swift. It's worth knowing what it does, because you'll copy patterns from it:

  1. It owns a Timer.publish(every: 1/60.0, on: .main, in: .common) timer.
  2. On each tick it stores the Date the timer delivers in an @State property, but only while a flag set by onAppear and cleared by onDisappear says the view is on screen. The timer keeps firing either way; ticks that arrive while the canvas is off screen are ignored, so SwiftUI doesn't redraw canvases you've scrolled past.
  3. It passes that Date to your effect closure along with the content and the geometry proxy.

The chapter's view then turns the date into elapsed time:

AnimatedMetalCanvasView(with: "Example 1 - Breathing") { content, proxy, date in
    content.colorEffect(ShaderLibrary.breathingGradient(
        .float2(proxy.size),
        .float(Float(date.timeIntervalSince(startDate)))
    ))
}

Because it reads the real date on each tick instead of adding 1/60, a late tick doesn't slow the animation; it just skips a frame. It's capped at about 60 updates per second. It's a Timer-based driver that measures time correctly, which is a good compromise for a scroll view full of animated canvases.

Functions of time

With a clean time arriving in seconds, the rest is choosing what to do with it. Four shapes cover most of what you'll write:

// 1. Linear Change - Constant speed movement
float linear(float time, float speed) {
    return time * speed;
}

// 2. Oscillation - Back and forth, the heartbeat of nature
float oscillate(float time, float frequency) {
    return sin(time * frequency * 6.28318);  // frequency in Hz
}

// 3. Pulsing - Sharp attack, slow decay (like a heartbeat)
float pulse(float time, float period) {
    float phase = fract(time / period);
    return pow(phase, 0.1) * (1.0 - phase);
}

// 4. Smooth Random - Organic variation
float smoothRandom(float time) {
    // Using multiple sine waves to create pseudo-random smooth motion
    return sin(time * 0.7) * 0.5 + 
           sin(time * 1.3) * 0.3 +
           sin(time * 2.1) * 0.2;
}

Linear change never stops growing, so you use it for things that wrap anyway: a phase you feed into sin, or a value you pass through fract. Oscillation goes back and forth between -1 and 1 forever. The pulse uses fract(time / period) to make a ramp that climbs from 0 to 1 and restarts every period seconds; pow(phase, 0.1) shoots up almost immediately and (1.0 - phase) brings it back down slowly, which gives the quick-rise, slow-fade shape of a heartbeat. The smooth random adds three sines with unrelated speeds, so the sum wanders without an obvious repeat.

Reading the speed of a sine wave

You'll see sin(time * k) everywhere, so it pays to know how fast it moves. sin completes one cycle when its input grows by 2π (about 6.283). So sin(time * k) repeats every 2π / k seconds:

  • sin(time) repeats every 6.28 s.
  • sin(time * 2.0) repeats every 3.14 s.
  • sin(time * 6.28318) repeats every 1 s. That's why oscillate multiplies by 6.28318: it lets you think in cycles per second (Hz) instead of radians.

And sin(...) * 0.5 + 0.5 maps the -1 to 1 range onto 0 to 1, which is the range you want for colors and for mix.

Your first living shader: breathing gradient

Breathing Gradient Animation

A mesmerizing gradient that breathes and flows using sine waves to create organic color transitions

[[ stitchable ]] half4 breathingGradient(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  // Create a breathing effect using sine waves
  float breathe = sin(time * 2.0) * 0.5 + 0.5;  // 0 to 1, period 2π/2 ≈ 3.14 seconds

  // Use breathing to modify gradient position
  float gradientPos = uv.y + breathe * 0.2 - 0.1;

  // Create smooth gradient with animated colors
  float3 color1 = float3(0.1, 0.3, 0.8);  // Deep blue
  float3 color2 = float3(0.8, 0.4, 0.6);  // Pink

  // Animate the colors too
  color1.r += sin(time * 1.5) * 0.2;
  color2.g += sin(time * 0.7) * 0.2;

  // Smooth gradient
  float3 gradientColor = mix(color1, color2, smoothstep(0.0, 1.0, gradientPos));

  return half4(gradientColor.r, gradientColor.g, gradientColor.b, 1.0);
}
SwiftUI Metal Shader

time is passed in like size, and the shader uses it in three places. Follow the middle row of the view (uv.y = 0.5) through one breath:

time      sin(time * 2.0)    breathe    gradientPos
------    ---------------    -------    -----------
0.00 s     0                 0.5        0.5
0.79 s     1                 1.0        0.6
2.36 s    -1                 0.0        0.4
3.14 s     0                 0.5        0.5

breathe * 0.2 - 0.1 swings between -0.1 and +0.1, so every row's position in the gradient slides up and down by a tenth of the view's height, and the whole gradient appears to rise and fall. On top of that, the blue end's red channel and the pink end's green channel each drift on their own sine (1.5 and 0.7), so the two end colors never line up with the breathing in the same way twice.

Core animation techniques

Controlled Chaos Pattern

Harmonic layers creating pleasing interference patterns using 1x, 2x, and 4x base frequencies for organic motion

[[ stitchable ]] half4 controlledChaos(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  // Three layers with HARMONIC relationships (1x, 2x, 4x)
  // This creates pleasing interference instead of chaos
  float layer1 = sin((uv.x + time * 0.1) * 6.28318);      // Base frequency
  float layer2 = sin((uv.y + time * 0.2) * 6.28318 * 2.0) * 0.5;  // Octave
  float layer3 = sin((uv.x + uv.y + time * 0.4) * 6.28318 * 4.0) * 0.25;  // Two octaves

  // Combine with proper amplitude weighting
  float pattern = layer1 + layer2 + layer3;

  // Normalize to 0-1 range
  pattern = pattern * 0.4 + 0.5;

  // Create sophisticated color mapping
  float3 finalColor = float3(
      pattern * 0.6 + 0.2,
      pattern * 0.4 + 0.3,
      pattern * 0.8 + 0.1
  );

  return half4(finalColor.r, finalColor.g, finalColor.b, 1.0);
}
SwiftUI Metal Shader

Each layer is a wave that slides across the view. Work out how long each one takes to repeat (the value inside sin has to grow by 2π, so the bracket has to grow by 1, divided by the multiplier outside it):

  • layer1: time * 0.1 must grow by 1, so it repeats every 10 s.
  • layer2: time * 0.2 * 2.0 must grow by 1, so every 2.5 s.
  • layer3: time * 0.4 * 4.0 must grow by 1, so every 0.625 s.

2.5 and 0.625 both divide 10 evenly, so after 10 seconds all three layers are back where they started at the same moment, and the whole pattern repeats exactly. That's what makes a seamless loop: pick speeds whose periods all fit a whole number of times into one common period. If you record this effect, a 10 second clip loops with no visible seam. It also means you could wrap time on the Swift side with truncatingRemainder(dividingBy: 10) and nothing would change on screen.

The amplitudes halve each layer (1, 0.5, 0.25), so the big slow wave dominates and the faster ones add detail. The sum can range from -1.75 to 1.75, so * 0.4 + 0.5 maps it to roughly -0.2 to 1.2. The comment says 0 to 1, which is true most of the time; the extremes need all three layers to peak together and are rare.

2. Phase offsets: the same motion, out of step

Smooth Color Flow

Rich color transitions with each RGB channel animated at different frequencies and cross-influence for complex color mixing

[[ stitchable ]] half4 colorFlow(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;

  // Create smooth color transitions using sine waves
  // Each color channel has different frequency for rich variation
  float r = sin(time * 0.7 + uv.x * 3.14159) * 0.5 + 0.5;
  float g = sin(time * 1.1 + uv.y * 3.14159) * 0.5 + 0.5;
  float b = sin(time * 1.3 + length(uv - 0.5) * 6.28318) * 0.5 + 0.5;

  // Add some cross-influence for more interesting colors
  r += g * 0.2;
  g += b * 0.2;
  b += r * 0.2;

  // Normalize
  float3 finalColor = normalize(float3(r, g, b)) * 0.8;

  return half4(finalColor.r, finalColor.g, finalColor.b, 1.0);
}
SwiftUI Metal Shader

You met phase in Chapter 4: adding a number inside sin shifts where the wave starts. Here it does the work of spreading one animation across space. In sin(time * 0.7 + uv.x * 3.14159), every pixel runs the same red oscillation, but a pixel on the right edge (uv.x = 1) is π ahead of one on the left edge (uv.x = 0). Half a cycle ahead means that when the left edge is at its reddest, the right edge is at its least red, and the bands of color appear to travel across the view.

Each channel uses a different phase source: red follows uv.x, green follows uv.y, blue follows the distance from the center (so blue moves in rings). They also run at different speeds (0.7, 1.1, 1.3), so the mix of the three keeps changing. The cross-influence lines feed a bit of each channel into the next. normalize then scales the color so its length is 1, which keeps the brightness steady while the hue moves, and * 0.8 brings it down from full intensity.

3. Morphing shapes

Organic Morphing Blob

A dynamic blob that morphs using multiple harmonic sine waves and polar coordinates for organic, breathing motion

[[ stitchable ]] half4 morphingBlob(
  float2 position,
  half4 color,
  float2 size,
  float time
) {
  float2 uv = position / size;
  float2 center = uv - 0.5;

  // Create morphing blob using multiple sine waves
  float angle = atan2(center.y, center.x);
  float dist = length(center);

  // Base radius that changes over time
  float radius = 0.3;

  // Add multiple harmonics for organic shape
  radius += sin(angle * 3.0 + time * 2.0) * 0.05;
  radius += sin(angle * 5.0 - time * 3.0) * 0.03;
  radius += sin(angle * 7.0 + time * 1.5) * 0.02;

  // Breathing effect
  radius *= 1.0 + sin(time * 3.0) * 0.1;

  // Create smooth blob
  float blob = 1.0 - smoothstep(radius - 0.02, radius + 0.02, dist);

  // Animated colors
  float3 blobColor = float3(
      0.5 + sin(time * 1.1) * 0.3,
      0.5 + sin(time * 1.7) * 0.3,
      0.8 + sin(time * 2.3) * 0.2
  );

  return half4(blobColor.r * blob, blobColor.g * blob, blobColor.b * blob, blob);
}
SwiftUI Metal Shader

This is a circle in polar coordinates whose radius depends on the angle. sin(angle * 3.0) adds three bumps around the edge, angle * 5.0 adds five, and angle * 7.0 adds seven. Adding time to each term rotates those bumps around the center. The middle term subtracts time, so its bumps turn the other way, and the three sets slide over each other. The edge never settles into one fixed shape. Then the whole radius is scaled by up to 10% on its own sine for a breathing pulse.

Look at the return line. The color is multiplied by blob and blob is also the alpha. SwiftUI expects colors from a shader in premultiplied alpha, where the RGB channels are already multiplied by alpha. Outside the blob, blob is 0, so the pixel is (0, 0, 0, 0), fully transparent. On the soft edge, a pixel with blob = 0.5 comes out as half the color with alpha 0.5, which is the correct premultiplied value for a half-transparent pixel. If you returned half4(blobColor, blob) instead, the edge would come out too bright.

4. Particle flow

Flowing Particle System

Animated particles following flowing sine wave paths with varying sizes and rainbow colors based on particle ID

[[ stitchable ]] half4 flowingParticles(
  float2 position,
  half4 color,
  float2 size,
  float time,
  float particleCount  // 10 to 50
) {
  float2 uv = position / size;

  float particles = 0.0;
  float3 particleColor = float3(0.0);

  // Create flowing particles
  for (int i = 0; i < int(particleCount); i++) {
      // Unique flow for each particle
      float id = float(i) / particleCount;

      // Create flowing path using sine waves
      float pathX = sin(time * (0.5 + id) + id * 6.28) * 0.3 + 0.5;
      float pathY = fract(time * (0.3 + id * 0.5) + id);

      float2 particlePos = float2(pathX, pathY);

      // Distance to particle
      float dist = length(uv - particlePos);

      // Particle size varies
      float size = 0.01 + sin(time * 3.0 + id * 6.28) * 0.005;

      // Soft particle
      float particle = 1.0 - smoothstep(0.0, size, dist);

      // Accumulate
      particles += particle;

      // Color based on position
      float3 pColor = float3(
          0.5 + sin(id * 6.28) * 0.5,
          0.5 + sin(id * 6.28 + 2.094) * 0.5,
          0.5 + sin(id * 6.28 + 4.189) * 0.5
      );

      particleColor += pColor * particle;
  }

  return half4(particleColor.r, particleColor.g, particleColor.b, particles);
}
SwiftUI Metal Shader

There are no particle objects here. Every pixel loops over all particles, works out where each one is at this time, and adds up how close it is to them. Each particle gets an id between 0 and 1 and uses it in three ways:

  • As a phase offset (+ id * 6.28 in pathX), so particles start at different points of the same side-to-side sway.
  • As a speed change (0.5 + id and 0.3 + id * 0.5), so they don't move in lockstep.
  • In pathY, fract(...) turns ever-growing time into a 0 to 1 ramp. Each particle falls from the top (y = 0) to the bottom and reappears at the top, because y grows downward in SwiftUI.

The colors use phase offsets too: red, green and blue are the same sine of id, shifted by 2.094 (2π/3) and 4.189 (4π/3), a third of a cycle apart. As id goes from 0 to 1, that walks around the color wheel, which is a compact way to give every particle a different hue.

The cost of this shader grows with particleCount, because every pixel runs the loop. The Xcode project passes 100 particles to show the effect at full density; the performance section below comes back to this.

Easing over time

Chapter 7 used smoothstep to ease a transition. Here you'll ease a motion that repeats forever. The recipe has three steps:

  1. Turn endless time into a repeating 0 to 1 ramp with fract(time * speed).
  2. Pass that ramp through an easing curve, which keeps 0 at 0 and 1 at 1 but changes how fast it moves in between.
  3. Use the eased value as the t in mix(start, end, t).

Here are the curves:

// Linear - robotic, unnatural
float linear(float t) {
    return t;
}

// Ease In - slow start, fast end (falling object)
float easeIn(float t) {
    return t * t;
}

// Ease Out - fast start, slow end (thrown ball slowing down)
float easeOut(float t) {
    return 1.0 - (1.0 - t) * (1.0 - t);
}

// Ease In Out - slow start and end (professional, smooth)
float easeInOut(float t) {
    return t < 0.5 
        ? 2.0 * t * t 
        : 1.0 - pow(-2.0 * t + 2.0, 2.0) / 2.0;
}

// Bounce - playful, energetic
float bounce(float t) {
    const float n1 = 7.5625;
    const float d1 = 2.75;
    
    if (t < 1.0 / d1) {
        return n1 * t * t;
    } else if (t < 2.0 / d1) {
        t -= 1.5 / d1;
        return n1 * t * t + 0.75;
    } else if (t < 2.5 / d1) {
        t -= 2.25 / d1;
        return n1 * t * t + 0.9375;
    } else {
        t -= 2.625 / d1;
        return n1 * t * t + 0.984375;
    }
}

// Elastic - springy, dynamic
float elastic(float t) {
    const float c4 = (2.0 * 3.14159) / 3.0;
    
    return t == 0.0 ? 0.0 
         : t == 1.0 ? 1.0
         : pow(2.0, -10.0 * t) * sin((t * 10.0 - 0.75) * c4) + 1.0;
}

easeIn squares t: at t = 0.5 it returns 0.25, so the first half of the time covers only a quarter of the distance and the rest is covered quickly. easeOut is the mirror image. easeInOut uses easeIn for the first half and a flipped copy for the second. bounce is four parabolas joined end to end, each smaller than the last, like a ball losing energy. elastic is a sine wave whose size shrinks by pow(2.0, -10.0 * t), so it overshoots past 1 and settles.

Applying easing to an animation

Easing Functions Demonstration

Interactive showcase of different easing curves (linear, ease-in, ease-out, ease-in-out, bounce, elastic) with animated circle and trail

[[ stitchable ]] half4 easedAnimation(
  float2 position,
  half4 color,
  float2 size,
  float time,
  float easingType  // 0-5 for different curves
) {
  float2 uv = position / size;

  // Create a looping animation phase (0 to 1)
  float phase = fract(time * 0.3);  // repeats every 1/0.3 ≈ 3.3 seconds

  // Apply selected easing
  float easedPhase = phase;  // Default linear

  if (easingType < 0.5) {
      easedPhase = phase;  // Linear
  } else if (easingType < 1.5) {
      easedPhase = easeIn(phase);
  } else if (easingType < 2.5) {
      easedPhase = easeOut(phase);
  } else if (easingType < 3.5) {
      easedPhase = easeInOut(phase);
  } else if (easingType < 4.5) {
      easedPhase = bounce(phase);
  } else {
      easedPhase = elastic(phase);
  }

  // Use eased phase to animate something visual
  float2 center = float2(0.5, 0.5);
  float2 animatedPos = mix(
      float2(0.2, 0.5),  // Start position
      float2(0.8, 0.5),  // End position
      easedPhase
  );

  // Draw animated circle
  float dist = length(uv - animatedPos);
  float circle = 1.0 - smoothstep(0.05, 0.06, dist);

  // Trail effect
  float trail = 0.0;
  for (int i = 1; i <= 10; i++) {
      float trailPhase = phase - float(i) * 0.02;
      if (trailPhase < 0.0) trailPhase += 1.0;

      // Apply same easing to trail
      float trailEased = trailPhase;
      if (easingType >= 3.5) {
          trailEased = easeInOut(trailPhase);  // Simplified for trail
      }

      float2 trailPos = mix(float2(0.2, 0.5), float2(0.8, 0.5), trailEased);
      float trailDist = length(uv - trailPos);
      trail += (1.0 - smoothstep(0.04, 0.05, trailDist)) * (1.0 - float(i) / 10.0);
  }

  // Color
  float3 finalColor = float3(trail * 0.3, trail * 0.5, trail * 0.8);
  finalColor += float3(circle);

  return half4(finalColor.r, finalColor.g, finalColor.b, 1.0);
}
SwiftUI Metal Shader

Trace the circle at time = 2.0 seconds:

  1. phase = fract(2.0 * 0.3) = fract(0.6) = 0.6
  2. With ease in: easedPhase = 0.6 * 0.6 = 0.36. With linear it would stay 0.6.
  3. mix(0.2, 0.8, 0.36) = 0.2 + 0.6 * 0.36 = 0.416. With linear: 0.2 + 0.6 * 0.6 = 0.56.

So at the same moment the eased circle is noticeably behind the linear one. It catches up in the last part of the loop, because both reach 0.8 when phase reaches 1.

The trail draws ten fainter circles at slightly earlier phases. To keep the snippet short, it only eases the trail for easingType 3 and above, and uses easeInOut for all three of those, so for ease in, ease out, bounce and elastic the trail doesn't follow the circle exactly. The version in the Xcode project fixes that: it routes every sample through one applyEasing(t, easingType) helper and draws a 30-sample motion blur that gets stronger as the circle moves faster.

One thing you'll notice in every mode: when phase wraps from 1 back to 0, the circle jumps from the right side to the left. That's fract doing its job. If you want the circle to go back and forth instead, use a triangle wave as the ramp: 1.0 - abs(fract(time * 0.3) * 2.0 - 1.0) climbs from 0 to 1 and back down to 0 every loop with no jump.

Performance

Every frame, the shader runs once per pixel. Note that it's per pixel even though position is in points: a 300 × 300 point canvas on a 3x screen is 900 × 900, about 810,000 pixels. Whatever your shader does, multiply it by that, then by the frame rate.

// EXPENSIVE: Complex calculations every frame
float expensiveAnimation(float time) {
    float result = 0.0;
    for (int i = 0; i < 100; i++) {
        result += sin(time * float(i) * 0.1) * cos(time * float(i) * 0.05);
    }
    return result;
}

// OPTIMIZED: Use mathematical identities
float optimizedAnimation(float time) {
    // Sum of sines can often be simplified
    // Or pre-calculate what doesn't change
    float baseFreq = sin(time);
    float harmonics = baseFreq * 0.5 + sin(time * 2.0) * 0.3 + sin(time * 3.0) * 0.2;
    return harmonics;
}

// EXPENSIVE: Recalculating static values
float2 rotatePoint(float2 p, float angle) {
    // Calculating sin/cos every pixel
    return float2(
        p.x * cos(angle) - p.y * sin(angle),
        p.x * sin(angle) + p.y * cos(angle)
    );
}

// OPTIMIZED: Calculate once, reuse
float2 rotatePointOptimized(float2 p, float sinAngle, float cosAngle) {
    // sin/cos passed in, calculated once per frame
    return float2(
        p.x * cosAngle - p.y * sinAngle,
        p.x * sinAngle + p.y * cosAngle
    );
}

The first pair is about the number of terms. The 100-term loop runs 200 trig calls per pixel; the three-term version runs three. They don't compute the same function, and that's the point: three well-chosen sines usually look just as rich, and the screen can't show you the difference. The same applies to flowingParticles with 100 particles. Each extra particle is another trip through the loop for every pixel.

The second pair is about work that's the same for every pixel. If angle depends only on time, every one of those 810,000 pixels computes the same sin(angle) and cos(angle). Compute them once in Swift and pass them in with .float(sin(angle)) and .float(cos(angle)).

Frame rate independence

Animations should depend on how many seconds have passed, not on how many frames have been drawn. The shader side is easy: if you write time * speed, speed is in units per second, whatever the frame rate. The trap is on the Swift side, in how you produce time:

// Frame-dependent: assumes every tick arrives exactly 1/60 s after the last
.onReceive(timer) { _ in timeValue += 1/60.0 }

// Frame-independent: measure how much real time has passed
.onReceive(timer) { now in timeValue = Float(now.timeIntervalSince(startDate)) }

With the first version, if the main thread is busy and ticks arrive late, timeValue falls behind the clock and the animation runs slow. The second version reads the actual date the timer delivers, so a late tick still produces the right time; you just see fewer frames. TimelineView and AnimatedMetalCanvasView both work the second way.

Common pitfalls

Pitfall 1: Letting time grow without a plan

// WRONG: Time keeps growing, eventually breaks
float bigNumber = sin(time * 1000.0);  // Precision loss after hours

// CORRECT: Use modulo or fract for stable loops
float stableLoop = sin(fract(time * 0.1) * 10.0 * 6.28318);

stableLoop is the same wave as sin(time * 6.28318): fract(time * 0.1) * 10.0 is time wrapped into 0 to 10, and because the wave completes a whole number of cycles in 10 seconds, the wrap doesn't show. The input to sin stays small.

What fract can't do is bring back precision that was lost before the value reached the shader. If time arrived as 800 million, it's already rounded to the nearest 64 seconds and fract just wraps a wrong number. So the main fix is the one from the start of the chapter: pass elapsed time from a start date. Large multipliers like * 1000.0 make things worse, because they magnify whatever rounding time has. One day into an animation, time is only accurate to about 0.008 s; multiply by 1000 and the input to sin is off by up to 8 radians, more than a full cycle.

Pitfall 2: Hard cuts

// Hard cut: jumps from 0 to 1 halfway through each second, then back to 0 when fract wraps
float jump = step(0.5, fract(time));

// Smooth both ways: fade in around 0.5, fade out just before fract wraps at 1.0
float t = fract(time);
float smooth = smoothstep(0.4, 0.6, t) * (1.0 - smoothstep(0.9, 1.0, t));

step switches instantly, so anything driven by it pops on and off. Replacing it with smoothstep(0.4, 0.6, t) softens the switch on, but fract still drops from 1 back to 0 at the end of every second, and the value would pop off there. The second factor fades it out over the last tenth of the second, so the value is already 0 when fract wraps. Whenever you build animation from fract, check what happens at the wrap.

Pitfall 3: Unrelated frequencies when you need a loop

// Unrelated frequencies: the sum never repeats exactly
float chaos = sin(time * 1.234) + sin(time * 5.678);

// Whole-number multiples of one base frequency: repeats every π seconds
float harmony = sin(time * 2.0) + sin(time * 4.0) + sin(time * 6.0);

Neither of these is wrong. They do different jobs. The harmony speeds are all multiples of 2, so all three waves line up again every π seconds (the period of the slowest one), and the motion has a regular rhythm that loops cleanly. The chaos speeds have no simple ratio, so the sum drifts and never repeats. That's what smoothRandom at the top of the chapter wants. Use related frequencies for loops and rhythmic motion, and unrelated ones for organic drift where a visible repeat would look mechanical.

Challenges

The challenge templates below use the simple Timer counter from Option 2 (timeValue += 1/60.0), and so do the solutions in the Xcode project. It keeps the templates short. If you see an animation slow down when the app is busy, switch to the elapsed-time version from the frame rate section.

Challenge 1: Flowing aurora

Flowing Aurora Example

Create an aurora shader that looks like the Northern Lights: curtains of light that ripple sideways over a night sky.

Requirements:

  • Use several layers of animated bands, each with its own speed
  • Colors should shift between green, blue, and purple
  • Movement should feel organic, not looping on an obvious rhythm
  • Shape each band like a hanging curtain, wavy along its length

Hint: one band is a horizontal line whose height changes with x and time, like y = 0.3 + sin(uv.x * 4.0 + time * 0.7) * 0.3. Brightness falls off with the distance from that line, for example exp(-abs(uv.y - y) * 3.0). The speed slider scales time before you use it, and intensity scales the brightness.

SwiftUI Template:

struct AuroraView: View {
    @State private var timeValue: Float = 0.0
    @State private var intensity: Float = 1.0
    @State private var speed: Float = 1.0
    
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Text("Aurora Borealis")
                .font(.title2)
                .padding()
            
            Rectangle()
                .fill(Color.black)
                .visualEffect { content, proxy in
                    content.colorEffect(ShaderLibrary.aurora(
                        .float2(proxy.size),
                        .float(timeValue),
                        .float(intensity),
                        .float(speed)
                    ))
                }
                .frame(height: 400)
            
            VStack(spacing: 15) {
                HStack {
                    Text("Intensity")
                    Slider(value: $intensity, in: 0.5...2.0)
                }
                
                HStack {
                    Text("Speed")
                    Slider(value: $speed, in: 0.5...2.0)
                }
            }
            .padding()
        }
        .onReceive(timer) { _ in
            timeValue += 1/60.0
        }
    }
}

Challenge 2: Interactive ripples

Ripple Effect Example

Create an interactiveRippleDistortion shader that makes ripples spread out from wherever the user drags, bending the content underneath like the surface of water.

This one is a distortionEffect, not a colorEffect. A distortion shader doesn't return a color. It returns a float2: the position in the original content to sample for this pixel. Return position unchanged and nothing moves; return position plus a small offset and the pixel shows content from slightly further away. Because it can't change colors, the ripple shows up as the content bending.

The template stores every ripple in Swift (normalized x, y, the timeValue when it started, and a random intensity) and flattens them into one [Float] passed with .floatArray(...). On the Metal side, a float array arrives as a pointer plus a count, so your signature looks like this:

[[ stitchable ]] float2 interactiveRippleDistortion(
    float2 position,
    float2 size,
    float time,
    device const float* rippleData, int dataCount
)

Each ripple takes four floats, so ripple i starts at rippleData[i * 4], and its age is time - rippleData[i * 4 + 2].

Requirements:

  • Each ripple is a ring that expands outward from its center as it ages and fades out
  • Several ripples can be active at once, and their displacements add together where they overlap
  • Push pixels along the direction away from each ripple's center
  • Ripples older than 3 seconds have no effect (the template also removes them from the array)

Keep the offset you return smaller than maxSampleOffset (50 points here). SwiftUI uses that value to know how far outside a pixel the shader may sample, and content beyond it gets cut off.

The Xcode project also contains rippleEffect, a simpler colorEffect version that draws glowing rings around a fixed center instead of distorting content. It's a good warm-up if the distortion version feels like a big step.

SwiftUI Template:

struct InteractiveRippleView: View {
    @State private var timeValue: Float = 0.0
    @State private var ripples: [RippleData] = []
    @State private var lastRippleLocation: CGPoint? = nil
    
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Text("Interactive Ripple Effect")
                .font(.title2)
                .padding()
            
            GeometryReader { geometry in
                // Sample content to be distorted
                VStack(spacing: 20) {
                    Circle()
                        .fill(LinearGradient(
                            colors: [.blue, .purple, .pink],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        ))
                        .frame(width: 100, height: 100)
                    
                    Text("Drag to create ripples")
                        .font(.headline)
                        .foregroundColor(.white)
                    
                    Rectangle()
                        .fill(LinearGradient(
                            colors: [.green, .yellow],
                            startPoint: .leading,
                            endPoint: .trailing
                        ))
                        .frame(height: 50)
                        .cornerRadius(10)
                        .padding(.horizontal)
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
                .background(Image(.abstractUnsplash).resizable().opacity(0.4))
                .visualEffect { content, proxy in
                    // Interleave all ripple data into a single array
                    var rippleData: [Float] = []
                    for ripple in ripples {
                        rippleData.append(ripple.x)
                        rippleData.append(ripple.y)
                        rippleData.append(ripple.startTime)
                        rippleData.append(ripple.intensity)
                    }
                    
                    return content.distortionEffect(
                        ShaderLibrary.interactiveRippleDistortion(
                            .float2(proxy.size),
                            .float(timeValue),
                            .floatArray(rippleData)
                        ),
                        maxSampleOffset: .init(width: 50, height: 50)
                    )
                }
                .gesture(
                    DragGesture(minimumDistance: 0)
                        .onChanged { value in
                            // Add ripples during drag with some spacing
                            if let lastLocation = lastRippleLocation {
                                let distance = hypot(
                                    value.location.x - lastLocation.x,
                                    value.location.y - lastLocation.y
                                )
                                // Only add new ripple if we've moved at least 20 points
                                if distance > 20 {
                                    addRipple(at: value.location, in: geometry.size)
                                    lastRippleLocation = value.location
                                }
                            } else {
                                // First ripple in the drag
                                addRipple(at: value.location, in: geometry.size)
                                lastRippleLocation = value.location
                            }
                        }
                        .onEnded { value in
                            // Add final ripple and reset
                            addRipple(at: value.location, in: geometry.size)
                            lastRippleLocation = nil
                        }
                )
            }
            .frame(height: 400)
            .border(Color.gray, width: 1)
            
            Text("Drag across the view to create ripple trails")
                .font(.caption)
                .foregroundColor(.secondary)
                .padding()
        }
        .onReceive(timer) { _ in
            timeValue += 1/60.0
            cleanupOldRipples()
        }
    }
    
    private func addRipple(at location: CGPoint, in size: CGSize) {
        let ripple = RippleData(
            x: Float(location.x / size.width),
            y: Float(location.y / size.height),
            startTime: timeValue,
            intensity: Float.random(in: 0.8...1.2)
        )
        
        ripples.append(ripple)
        
        // Limit to 15 concurrent ripples for performance (increased from 10)
        if ripples.count > 15 {
            ripples.removeFirst()
        }
    }
    
    private func cleanupOldRipples() {
        ripples.removeAll { timeValue - $0.startTime > 3.0 }
    }
}

struct RippleData {
    let x: Float
    let y: Float
    let startTime: Float
    let intensity: Float
}

Challenge 3: Particle vortex

Particle Vortex Example

Create a particleVortex shader where particles spiral in toward the center, like water going down a drain.

Requirements:

  • Particles follow spiral paths: the angle grows with time while the radius shrinks
  • Particles turn faster the closer they get to the center
  • Color depends on colorMode: 0 colors by speed, 1 by distance from the center, 2 cycles through a rainbow
  • Particles fade in and out smoothly, and a particle that reaches the center starts again on the outside instead of disappearing for good

Hint: radius = startRadius * exp(-t * 0.3) shrinks smoothly toward 0 without ever reaching it, and making the angular speed larger as radius gets smaller gives you the drain-like acceleration. For the restart, find how long a particle takes to reach a small threshold radius and use fmod with that duration, the same wrap-around trick as fract.

SwiftUI Template:

struct ParticleVortexView: View {
    @State private var timeValue: Float = 0.0
    @State private var particleCount: Float = 30.0
    @State private var vortexStrength: Float = 1.0
    @State private var colorMode: Float = 0.0  // 0=speed-based, 1=position-based, 2=rainbow
    
    let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
    
    var body: some View {
        VStack {
            Text("Particle Vortex")
                .font(.title2)
                .padding()
            
            Rectangle()
                .fill(Color.black)
                .visualEffect { content, proxy in
                    content.colorEffect(ShaderLibrary.particleVortex(
                        .float2(proxy.size),
                        .float(timeValue),
                        .float(particleCount),
                        .float(vortexStrength),
                        .float(colorMode)
                    ))
                }
                .frame(height: 400)
            
            VStack(spacing: 15) {
                HStack {
                    Text("Particles: \(Int(particleCount))")
                    Slider(value: $particleCount, in: 10...50, step: 1)
                }
                
                HStack {
                    Text("Vortex Strength")
                    Slider(value: $vortexStrength, in: 0.5...3.0)
                }
                
                Picker("Color Mode", selection: Binding(
                    get: { Int(colorMode) },
                    set: { colorMode = Float($0) }
                )) {
                    Text("Speed").tag(0)
                    Text("Position").tag(1)
                    Text("Rainbow").tag(2)
                }
                .pickerStyle(SegmentedPickerStyle())
            }
            .padding()
        }
        .onReceive(timer) { _ in
            timeValue += 1/60.0
        }
    }
}

Want the Challenges Solutions?

Get the full Xcode project with solutions to all challenges, bonus examples, and clean, runnable code.

Get the Full Project →

Validation Questions

Before proceeding to Chapter 10:

  1. Why doesn't withAnimation animate a value you pass to a shader with .float(...)?

SwiftUI only interpolates values that are exposed as animatable data, such as a view's opacity or a modifier's animatableData. A shader argument isn't one, so when you change the @State value inside withAnimation, the view redraws once with the final value and the shader jumps there. To animate it, put the shader in a ViewModifier that conforms to Animatable and exposes the value as animatableData; SwiftUI then rebuilds the shader with an interpolated value on every frame. For effects that run continuously, drive time with TimelineView(.animation) instead.

  1. How are frequency, period and wavelength related in shader animations?

Frequency is cycles per second and period is seconds per cycle, so period = 1 / frequency. For sin(time * k), the period is 2π / k seconds: sin(time * 2.0) repeats every 3.14 s. Wavelength is the same idea in space: the distance over which a pattern like sin(uv.x * k) repeats, 2π / k in UV units. A higher frequency means a shorter period and more cycles in the same amount of time.

  1. Why do you pass the time since a start date instead of Date().timeIntervalSinceReferenceDate, and what else keeps long animations precise?

timeIntervalSinceReferenceDate is around 800 million seconds. Converted to Float, values that large are 64 seconds apart, so the shader gets the same time for about a minute and then jumps. Subtract a start date in Double first, then convert the small result. For effects that run for hours, wrap the elapsed time on the Swift side to a period the animation repeats on (truncatingRemainder(dividingBy:)), keep time as float rather than half in the shader, and avoid multiplying it by very large numbers. Using fract inside the shader keeps the input to sin small, but it can't recover precision that was already lost before the value arrived.

  1. What's the difference between Timer, CADisplayLink and TimelineView for driving shader time?

A Timer fires on the main run loop at the interval you ask for, so it doesn't follow the display's refresh rate, and if you add a fixed 1/60 per tick, late ticks make the animation run slow. CADisplayLink calls you once per screen refresh with a timestamp you can turn into elapsed time; it's a UIKit-level tool you manage yourself. TimelineView(.animation) gives you display-synced updates and the current date inside SwiftUI with no setup, and .animation(minimumInterval:paused:) lets you pause it or cap its rate. For SwiftUI shaders it's usually the best choice.

  1. When do you want frequencies that are whole-number multiples of each other, and when do you want unrelated ones?

If every frequency is a whole-number multiple of one base frequency (1x, 2x, 4x), all the waves return to their starting point together after one period of the base wave, so the motion has a steady rhythm and loops seamlessly. controlledChaos repeats exactly every 10 seconds this way. Frequencies with no simple ratio (0.7, 1.3, 2.1) never line up again, so the sum never repeats. That's the right choice for organic drift, where a visible loop would look mechanical.

  1. Why use easing functions instead of linear interpolation?

Real objects speed up and slow down; they don't start and stop at full speed. A linear ramp moves at constant speed and then stops dead, which reads as mechanical. Easing curves keep the same start and end but change the speed along the way (slow start, slow finish, overshoot, bounce), and in a shader you apply them by passing the fract(time * speed) ramp through the curve before using it in mix.

Further Exploration

  • Fourier transforms: decomposing complex motion into a sum of simple frequencies
  • Lissajous curves: the patterns you get when x and y oscillate at different frequencies
  • Perlin noise over time: smooth random motion without stacking sine waves
  • Reaction-diffusion: patterns that evolve frame by frame from simple local rules

Next Chapter Preview: So far every shader has computed its color from position, time and the arguments you pass. Chapter 10 introduces layerEffect, which gives your shader the rendered view itself to sample. With access to neighboring pixels you'll build blurs, convolution filters, bloom and other image-processing effects.