The GPU Canvas

What a shader is

You may have heard shaders described as "programs that color pixels." That's true, and it's also the reason they feel strange the first time you write one, so let me be precise about what it means.

A shader is a small function that the GPU runs once for every pixel, and it runs those calls in parallel. Each call is independent: it gets its own inputs, returns its own result, and has no way to see what any other call is doing or has done. You can't keep a running total, you can't ask the pixel to your left what color it chose, and you can't decide that pixel 500 should run before pixel 501. Everything that makes shaders fast comes from that restriction, and almost every "how do I do this in a shader?" question in this course comes back to it.

The good news for a SwiftUI developer is that you don't have to learn GPU architecture, render pipelines, or GPU memory management to use shaders. SwiftUI handles all of that. You write the per-pixel function, attach it to a view with a modifier, and SwiftUI runs it.

Shader stages SwiftUI exposes

When you program Metal directly, a GPU program is built from several kinds of shader functions, each with its own job:

  1. Vertex functions take the corners of your 3D or 2D shapes and work out where they land on screen.
  2. Fragment functions run once for every pixel those shapes cover and decide the pixel's color.
  3. Kernel (compute) functions do general number crunching on the GPU, with no drawing involved.
  4. Newer GPUs also support tile, mesh, and object functions for more specialized rendering setups.

(If you've read about OpenGL or DirectX, you may know geometry shaders. Metal doesn't have them.)

SwiftUI doesn't let you write vertex or compute functions. What it gives you are three view modifiers, and each one takes a function that SwiftUI calls once per pixel of the view. That is the fragment shader's job, which is why I'll use the terms "fragment shader" and "SwiftUI shader" fairly loosely in this course. The three modifiers differ in what your function receives and what it returns:

  • .colorEffect gives your function the pixel's position and its current color, and expects a new color (half4) back. Use it for tints, gradients, color filters, and generated patterns.
  • .distortionEffect gives your function only the pixel's position, and expects a position (float2) back: the place in the view to take this pixel's color from. Use it for waves, ripples, magnifiers, and bends.
  • .layerEffect gives your function the pixel's position and the whole rendered view, and expects a new color (half4) back. Use it for blurs, pixelation, and anything else that needs to read neighboring pixels.

Here is one tiny example of each so you can see their shapes side by side. You don't need to understand every line yet; the rest of this chapter explains the pieces.

.colorEffect hands you the color and asks for a color back. This one turns the view's colors to their negatives:

[[ stitchable ]] half4 invert(float2 position, half4 color) {
    return half4(color.a - color.rgb, color.a);
}
Image("photo")
    .colorEffect(ShaderLibrary.invert())

.distortionEffect doesn't hand you a color at all. You return a position, and SwiftUI fills this pixel with whatever color the view has at that position. Returning position unchanged gives you the original view. This one shifts each row up or down by a sine wave, so straight horizontal lines come out wavy:

[[ stitchable ]] float2 sineWave(float2 position) {
    return float2(position.x, position.y + sin(position.x * 0.05) * 10.0);
}
Text("Wavy")
    .font(.largeTitle)
    .distortionEffect(ShaderLibrary.sineWave(), maxSampleOffset: CGSize(width: 0, height: 10))

maxSampleOffset tells SwiftUI the furthest any pixel will reach to read its color (here, 10 points vertically). SwiftUI needs it to know how much of the surrounding area to keep available.

.layerEffect gives you the whole rendered view as a SwiftUI::Layer that you can read from at any position with layer.sample(...). This one pixelates the view by making every pixel in an 8×8 point block read the color at the block's center:

#include <SwiftUI/SwiftUI_Metal.h>

[[ stitchable ]] half4 pixelate(float2 position, SwiftUI::Layer layer, float cellSize) {
    float2 cellCenter = (floor(position / cellSize) + 0.5) * cellSize;
    return layer.sample(cellCenter);
}
Image("photo")
    .layerEffect(ShaderLibrary.pixelate(.float(8)), maxSampleOffset: CGSize(width: 8, height: 8))

Notice the extra #include: SwiftUI::Layer is defined in SwiftUI's own Metal header, so any file with a layerEffect shader needs it.

Chapters 1 to 9 mostly use .colorEffect, because it is the simplest and covers a surprising amount of ground. Distortion shows up in Chapter 4, and Chapter 10 is all about layerEffect.

Why this course uses SwiftUI's approach

I could teach you Metal from the ground up, with vertex buffers and render pipelines. Before you saw a single colored pixel you would need setup code for the GPU device and command queue, an understanding of render passes, manual management of GPU buffers, and code to keep the CPU and GPU from stepping on each other's data.

SwiftUI's shader modifiers skip all of that. They are more limited than raw Metal (you can't draw 3D models with them, for example), but they work in any SwiftUI view, they need no setup beyond a .metal file, and they fit with the rest of SwiftUI: state, gestures, TimelineView, transitions. Every example in this course runs in an ordinary SwiftUI app.

What happens when SwiftUI runs your shader

Take this line:

Text("Hello World")
    .colorEffect(ShaderLibrary.myShader(.float(brightness)))

Here is what happens, step by step:

  1. SwiftUI draws the text as usual, producing a grid of pixels with colors.
  2. For each of those pixels, it calls myShader with:
    • the pixel's position in the view (float2 position)
    • the pixel's current color (half4 color)
    • your own arguments, in the order you passed them (here, brightness)
  3. Your function returns a new color for that pixel.
  4. SwiftUI puts the resulting pixels on screen in place of the original ones.

Note what is missing from that list: the size of the view. A .colorEffect shader does not know how big the view is unless you pass the size yourself as an argument. Chapter 2 shows how, using .visualEffect to read the view's size and pass it in with .float2(size). The other option is .boundingRect, covered in the parameter table below.

The shader mental model: a factory of workers

Imagine a factory with one worker per pixel, which means millions of workers for a full-screen view. Each worker:

  • knows only their own position (and, with .colorEffect, the color already at that spot)
  • can't talk to any other worker
  • must hand in exactly one color
  • follows the same instruction sheet as everyone else

Your job as a shader programmer is to write that one instruction sheet so that, when every worker follows it independently, the colors they hand in add up to a coherent picture.

This is why a ripple across an entire image is easy (every worker can compute "how far am I from the center, and what does the wave look like at that distance?" on their own), while something like "make this pixel the average of its neighbors" needs .layerEffect, which lets a worker read the finished input picture at other positions. Even then a worker can only read the input, never another worker's output.

Colors, positions, and the types that hold them

Metal is a C++-based language, so its types will look unfamiliar if you have only written Swift. Two of them show up in every shader in this course.

float2, half4, and friends

float is a 32-bit floating-point number, the same as Swift's Float. half is a 16-bit floating-point number, which Swift calls Float16. Half has much less precision: about three significant decimal digits.

The number after the type name means "a small vector of this many values":

  • float2 holds two floats, which you read as .x and .y. Positions use it.
  • half4 holds four halves, which you read as .r, .g, .b, .a (or .x, .y, .z, .w; they're the same slots). Colors use it.
  • You can grab several components at once: color.rgb is a half3 with the first three values.

Arithmetic works on all components at once. color.rgb * 0.5 halves red, green, and blue in a single expression, which is why shader code tends to be short.

Why half for colors and float for positions? Color channels live between 0 and 1, where three digits of precision is plenty, and the GPU can process 16-bit values more cheaply. Positions are a different story. Above 1024, a half can only represent whole numbers, so 1500.0 and 1500.4 become the same value, and above 2048 it can only represent even numbers. Keep positions, sizes, and time in float.

Color as numbers

In a shader, a color is four numbers between 0.0 and 1.0: red, green, blue, and alpha (opacity).

  • half4(1, 0, 0, 1): opaque pure red
  • half4(0.5, 0.5, 0.5, 1): opaque medium gray
  • half4(0, 0, 0, 1): opaque black
  • half4(0, 0, 0, 0): fully transparent

Premultiplied alpha

SwiftUI hands colors to your shader in premultiplied form, and expects them back that way. Premultiplied means the red, green, and blue values have already been multiplied by alpha. A 50% transparent white is not (1, 1, 1, 0.5); it is (1 × 0.5, 1 × 0.5, 1 × 0.5, 0.5), which is (0.5, 0.5, 0.5, 0.5).

This matters because of how the result is blended with whatever is behind the view:

on screen = shader.rgb + behind.rgb × (1 - shader.a)

Work it through for a pixel drawn over a black background (behind = 0):

correct:  half4(0.5, 0.5, 0.5, 0.5)  →  0.5 + 0 × 0.5  =  0.5  (50% white over black: mid gray)
wrong:    half4(1.0, 1.0, 1.0, 0.5)  →  1.0 + 0 × 0.5  =  1.0  (full white, not half-transparent)

Over a mid-gray background (behind = 0.5) the wrong version gives 1.0 + 0.5 × 0.5 = 1.25, which clips to white. A color whose RGB values are larger than its alpha isn't a valid premultiplied color, and it shows up brighter than you meant, as if it were added on top of the background.

Two habits keep you out of trouble:

  • When you modify the incoming color, it is already premultiplied. Scaling color.rgb and keeping color.a (as the brightness shader below does) stays valid.
  • When you build a color from scratch and want it partly transparent, multiply its RGB by the alpha you return.

Position as input

The position parameter tells your function which pixel it is computing:

  • x grows from left to right.
  • y grows from top to bottom. The origin (0, 0) is the view's top-left corner, the same as in SwiftUI layout.
  • The units are points in the view's own coordinate space, not device pixels and not values from 0 to 1.

That last point surprises people. On a 3× screen, a view 100 points wide is 300 pixels wide, so your shader runs 300 times across each row, and position.x goes from 0 to 100 in steps of about a third of a point. Since you don't get values from 0 to 1 for free, Chapter 2 starts by dividing position by the view's size to get them.

What a shader returns

A .colorEffect or .layerEffect shader returns a half4: the premultiplied red, green, blue, and alpha for this pixel. A .distortionEffect shader returns a float2 position instead.

Passing values from SwiftUI

Arguments

struct MyShader: View {
    @State private var brightness: Float = 1.0
    
    var body: some View {
        Image("photo")
            .colorEffect(ShaderLibrary.brighten(.float(brightness)))
    }
}

Each argument you pass becomes one parameter of the Metal function, after position and color. Whenever brightness changes, SwiftUI re-renders the view and the shader runs again with the new value.

Animating a shader over time

To animate a shader, give it a time value that changes every frame. TimelineView(.animation) re-renders its content once per display frame, so it's the usual way to drive a shader:

struct AnimatedShader: View {
    @State private var startDate = Date()
    
    var body: some View {
        TimelineView(.animation) { timeline in
            let time = timeline.date.timeIntervalSince(startDate)
            Rectangle()
                .colorEffect(ShaderLibrary.wave(.float(time)))
        }
    }
}

Two details in this snippet are deliberate.

First, the time is measured from startDate, so it starts at 0 and counts up in seconds. It's tempting to pass timeline.date.timeIntervalSinceReferenceDate directly, but that number is around 800 million (seconds since 2001), and a 32-bit float can't store such a large number precisely. At that size, consecutive float values are 64 seconds apart, so the time your shader sees only changes once a minute and the animation freezes or jumps.

Second, you might expect to animate a shader with withAnimation, by changing a @State value inside it. That doesn't work on its own: SwiftUI doesn't interpolate shader arguments, so the shader jumps straight to the final value. To animate an argument from one value to another with withAnimation, you have to wrap the shader in a view or modifier that conforms to Animatable. For continuous motion, TimelineView is simpler.

Data passing from SwiftUI to Metal

Every value you send to a shader goes through a Shader.Argument. Each argument type corresponds to a specific Metal parameter type, and your Metal function must declare them in the same order you pass them.

Supported data types

// SwiftUI → Metal Parameter Types
.float<T>(T)                    // → float
.float2(CGPoint)                // → float2 (from point.x, point.y)
.float2<T>(T, T)               // → float2
.float3<T>(T, T, T)            // → float3
.float4<T>(T, T, T, T)         // → float4
.color(Color)                   // → half4 (premultiplied in target color space)
.colorArray([Color])            // → device const half4 *ptr, int count
.image(Image)                   // → texture2d<half> (one per shader limit)
.floatArray([Float])            // → device const float *ptr, int count
.data(Data)                     // → device const void *ptr, int size_in_bytes
.boundingRect                   // → float4(x, y, width, height); you pass it, SwiftUI fills in the view's bounds

Note that the array types take two Metal parameters each: a pointer to the data and a count. You pass one argument in Swift, and SwiftUI supplies both.

Array data passing

When you need a list of values, such as several touch points, pack them into a .floatArray():

// SwiftUI Side - Multiple touch points
let touchPoints: [Float] = [
    Float(touch1.x), Float(touch1.y),
    Float(touch2.x), Float(touch2.y),
    Float(touch3.x), Float(touch3.y)
]

Rectangle()
    .colorEffect(ShaderLibrary.multiTouchRipple(.floatArray(touchPoints)))
// Metal Side - Receiving array data
[[stitchable]] half4 multiTouchRipple(
    float2 position, 
    half4 color, 
    device const float *touchPoints, 
    int count
) {
    for (int i = 0; i < count; i += 2) {
        float2 touchPos = float2(touchPoints[i], touchPoints[i + 1]);
        // Process each touch point...
    }
    return color;
}

count is the number of floats in the array (6 here), not the number of points, which is why the loop steps by 2 and reads an x and a y each time.

Beyond these types

If you need data the argument types can't carry, the next step up is leaving SwiftUI's shader modifiers and driving Metal yourself through an MTKView. This course stays within SwiftUI's modifiers.

Keep argument lists short

SwiftUI doesn't document a limit on how many arguments a shader can take, and shaders with long argument lists can fail without a clear error. Packing related values together (a position into a float2, an RGB color into a float3, a list into a floatArray) keeps the list short, and later chapters do this often.

Your first shader

Time to write one. In Xcode, add a new Metal file to your app target (File → New → File, then "Metal File"), call it Shaders.metal, and add this:

#include <metal_stdlib>
using namespace metal;

[[ stitchable ]] half4 solidRed(float2 position, half4 color) {
    return half4(1.0, 0.0, 0.0, 1.0);
}

Then in SwiftUI:

Rectangle()
    .colorEffect(ShaderLibrary.solidRed())

Run it and the rectangle is red.

Breaking down the code

  1. Headers and namespace

    #include <metal_stdlib>
    using namespace metal;
    

    These bring in Metal's standard library: vector types, and math functions like sin, mix, and clamp. Without the using namespace line you'd have to write metal::sin. Every shader file starts with these two lines.

  2. The function signature

    [[ stitchable ]] half4 solidRed(float2 position, half4 color)
    
    • [[ stitchable ]] is a Metal attribute (Metal attributes are written in double square brackets). It marks the function as one that can be linked into another GPU program at runtime. SwiftUI needs this because it links your function into the drawing code it already has. Leave it off and SwiftUI can't use the function.
    • half4 is the return type: the pixel's new red, green, blue, and alpha.
    • position and color are filled in by SwiftUI for every pixel. SwiftUI matches parameters by their order, not their names, so for .colorEffect the first must be a float2 and the second a half4. You could call them p and c and it would still work.
  3. The return

    return half4(1.0, 0.0, 0.0, 1.0);
    

    Opaque red for every pixel. The function ignores both inputs, so the result doesn't depend on where the pixel is or what color it was.

How ShaderLibrary finds your function

There is no Swift declaration for solidRed, so how does ShaderLibrary.solidRed() compile?

When you build the app, Xcode compiles every .metal file in the target into one Metal library and puts it in the app bundle as default.metallib. ShaderLibrary.default represents that library. ShaderLibrary uses Swift's dynamic member lookup, so ShaderLibrary.solidRed is shorthand for ShaderLibrary.default.solidRed, and any name you type is accepted by the compiler. It gives you a ShaderFunction naming the Metal function solidRed. Calling it with arguments, as in solidRed() or brighten(.float(0.5)), produces a Shader ready to pass to a modifier.

The lookup by name happens at runtime. If you misspell the name, or the function lacks [[ stitchable ]], Swift still compiles happily, and you only find out when you run the app and the effect isn't there. When a shader doesn't show up, check the spelling first.

(If your shaders live in a Swift package or another framework, ShaderLibrary.bundle(_:) loads the library from that bundle instead.)

Making it interactive

Now use the inputs. This shader scales the incoming color by a value you control:

[[ stitchable ]] half4 adjustableBrightness(
    float2 position, 
    half4 color,
    float brightness
) {
    return half4(color.rgb * brightness, color.a);
}
struct InteractiveShader: View {
    @State private var brightness: Float = 0.5
    var body: some View {
        Image("sample")
            .colorEffect(ShaderLibrary.adjustableBrightness(.float(brightness)))
            .overlay(alignment: .bottom) {
                Slider(value: $brightness, in: 0...1)
                    .padding()
            }
    }
}

Trace one pixel. Say its color is (0.8, 0.4, 0.2, 1.0), an orange, and the slider is at 0.5:

color.rgb * brightness  =  (0.8, 0.4, 0.2) * 0.5  =  (0.4, 0.2, 0.1)
return half4((0.4, 0.2, 0.1), 1.0)                 →  a darker orange

half4(someHalf3, alpha) builds a four-component color from a three-component one plus a fourth value. Keeping color.a means transparent parts of the image stay transparent. Because color arrives premultiplied, multiplying its RGB by a number between 0 and 1 keeps it valid.

.float(brightness) is the third parameter, float brightness, because it's the first argument after the two SwiftUI fills in.

Common pitfalls

Pitfall 1: thinking sequentially

// WRONG MENTAL MODEL
half4 badShader(float2 position, half4 color) {
    if (position.x == 0) {
        // "First, color the left edge..."
    }
    // NO! Every pixel executes simultaneously
}

There is no "first" in a shader. Each call answers one question: "what color is this pixel?" To color the left edge differently, every pixel checks whether it is on the left edge and picks its color accordingly. (Also, because positions are in points and land on pixel centers, position.x is rarely exactly 0. Compare against a range, like position.x < 10.0.)

Pitfall 2: color range confusion

// WRONG - Using 0-255 range
return half4(255, 0, 0, 1); 

// CORRECT - Using 0-1 range
return half4(1.0, 0.0, 0.0, 1.0);

If you have a color as 0 to 255 values from a design tool, divide each by 255.

Pitfall 3: ignoring alpha

// Alpha = 0 with non-zero RGB is not a valid premultiplied color:
// instead of disappearing, it adds red on top of whatever is behind
return half4(1.0, 0.0, 0.0, 0.0);

// To make a pixel invisible, return all zeros
return half4(0.0);

// Usually you want to keep the original alpha. If newColor is a fresh
// (non-premultiplied) color, multiply its RGB by that alpha too
return half4(newColor.rgb * color.a, color.a);

Pitfall 4: SwiftUI parameter mismatches

// WRONG - Type mismatch
.colorEffect(ShaderLibrary.myShader(.float2(size)))  // Shader expects a float; Swift can't check this and compiles it anyway

// CORRECT - Match types exactly
.colorEffect(ShaderLibrary.myShader(.float(brightness)))

The Swift compiler never sees your Metal function's signature, so it can't warn you when the arguments don't match. The mistake only shows up at runtime as a missing or wrong effect. When that happens, compare your Swift arguments against the Metal parameters one by one, in order.

Your shader as a function

It helps to think of a shader as a math function from inputs to a color:

f(position, color, parameters) → new_color

For solidRed:
f((0, 0), any_color, no_params) → (1, 0, 0, 1)
f((100, 200), any_color, no_params) → (1, 0, 0, 1)
f(anywhere, anything, nothing) → red

solidRed is a constant function: every input gives the same output. adjustableBrightness depends on the input color but not the position:

f((10, 20),  (0.8, 0.4, 0.2, 1), 0.5) → (0.4, 0.2, 0.1, 1)
f((300, 50), (0.8, 0.4, 0.2, 1), 0.5) → (0.4, 0.2, 0.1, 1)   same color in, same color out

Neither one uses position yet. Once the output depends on position, you get gradients, shapes, and patterns. That's Chapter 2.

What we're building toward

The bonus section of the course project uses the same techniques you'll learn in these chapters for larger effects: a holographic sticker, audio visualization, neon lights, refracting glass, image filters, and custom view transitions. Each is built from the same pieces: a per-pixel function, a few arguments from SwiftUI, and one of the three effect modifiers.

Challenges

Challenge 1: basic colors with SwiftUI

Challenge 1 Write three shaders, solidRed, solidGreen, and solidBlue, each returning one opaque color. Then build a SwiftUI view with three buttons that switch which shader is applied to a single view.

Test on a Rectangle(), then try a Text("Hello") and see which pixels change.

Tip: ShaderLibrary.solidRed() returns a Shader, so a computed property of type Shader with a switch over the selected button is an easy way to choose one.

Challenge 2: interactive brightness

Challenge 2 Write a brightnessControl shader that takes a float brightness parameter and multiplies the incoming color's RGB by it, keeping alpha. Build a SwiftUI view with:

  • an image with the shader applied
  • a slider controlling brightness from 0.0 to 2.0 (values above 1 brighten the image, values below 1 darken it)
  • a label showing the current value

Notice how bright areas turn white above 1.0: once a channel goes past 1, it clips.

Challenge 3: color channel isolation

Challenge 3 Write three shaders that each keep one channel of the incoming color and set the other two to 0:

  • redChannel keeps only red
  • greenChannel keeps only green
  • blueChannel keeps only blue

Keep the original alpha in all three. Add a fourth shader that returns color unchanged, so you can switch back to the original image, and use a segmented Picker to switch between the four on the same image.

Challenge 4: simple flag creator

Challenge 4 Build a three-stripe flag from three rectangles in an HStack, each with a color shader:

  • Start with France: blue (0, 0.3, 0.6), white (1, 1, 1), red (1, 0, 0).
  • Add a ColorPicker for each stripe so the user can change its color.

Hint: you don't need a separate shader per stripe. Write one shader with a float3 parameter for the stripe's color and apply it three times with different arguments. To get the three numbers out of a SwiftUI Color, convert it to a CGColor and read its components, or use Color.resolve(in:). (Alternatively, pass the color with .color(...) and take a half4 parameter, which is already premultiplied.)

Extra: add preset buttons for other three-stripe flags, such as Italy.

Challenge 5: animated pulse

Challenge 5 Write a pulsingColor shader that:

  • takes a float time parameter
  • uses sin(time) to move smoothly back and forth between two colors
  • is driven by TimelineView

sin returns values from -1 to 1. To blend between two colors you want a value from 0 to 1, so compute sin(time) * 0.5 + 0.5. Metal's mix(a, b, t) then returns a when t is 0, b when t is 1, and a blend in between. Multiply time by a constant inside the sin to make the pulse faster or slower.

Pass elapsed seconds since the view appeared, not the raw date (see "Animating a shader over time" above for why):

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

    var body: some View {
        TimelineView(.animation) { timeline in
            Rectangle()
                .colorEffect(ShaderLibrary.pulsingColor(.float(timeline.date.timeIntervalSince(startDate))))
        }
    }
}

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 moving on to Chapter 2, check that you can answer these:

  1. Why does a shader return half4 instead of half3?

The fourth component is alpha, the pixel's opacity. A half4 holds red, green, blue, and alpha, where alpha 1.0 is fully opaque and 0.0 is fully transparent. Without alpha, a shader couldn't make any part of a view transparent or keep the transparency the view already had.

  1. What happens if you return half4(1, 1, 1, 0.5)?

You might expect a 50% transparent white, but SwiftUI treats shader colors as premultiplied alpha, where RGB has already been multiplied by alpha. (1, 1, 1, 0.5) has RGB larger than its alpha, so it isn't a valid premultiplied color, and it renders brighter than intended: over black it shows as full white instead of mid gray. The correct 50% transparent white is half4(0.5, 0.5, 0.5, 0.5).

  1. Why can't one pixel ask another pixel what color it is?

Because the GPU runs your function for all pixels in parallel, and each call is independent: there's no shared state and no order in which pixels finish, so there's no "other pixel's result" to ask about. If you need to read the view's colors at other positions, .layerEffect lets you sample the original input, but never another call's output.

  1. How do you pass a Float parameter from SwiftUI to a shader?

Wrap it in .float(value) when calling the shader, for example .colorEffect(ShaderLibrary.myShader(.float(brightness))), and declare a matching float parameter in the Metal function right after position and color.

  1. What's the difference between .colorEffect and .distortionEffect?

.colorEffect gives your function the pixel's position and color and expects a new color back. .distortionEffect gives it only the position and expects a position back: the place in the view to take this pixel's color from. Use .colorEffect to change colors (tints, gradients, patterns) and .distortionEffect to move content around (ripples, waves, magnification). .distortionEffect also needs a maxSampleOffset saying how far a pixel can reach.

  1. Why use half4 instead of float4 for colors?

Color channels sit between 0 and 1, where half's 16-bit precision (about three significant digits) is enough. Using half halves the memory and bandwidth compared with 32-bit float, and the GPU can process it more cheaply. Positions, sizes, and time need float, because half can't represent large values precisely.

Further Exploration

  • Metal Performance Shaders: Apple's framework of ready-made, optimized GPU image-processing and math functions
  • GPU architecture: how GPUs run the same instructions on many pixels at once (SIMD execution)
  • Color spaces: sRGB versus linear color, and why it changes how blending looks
  • SwiftUI modifiers: how shader effects combine with other modifiers like .clipShape and .opacity, and how modifier order changes the result

Next Chapter Preview: You can fill a view with solid colors and control them from SwiftUI, but so far every pixel does the same thing regardless of where it is. Chapter 2 puts the position parameter to work: you'll convert it into coordinates that don't depend on the view's size, and use them to draw gradients, shapes, and patterns.