Quick Answer: In SwiftUI,
layerEffectpasses your Metal shader the rendered view as aSwiftUI::Layer, and you read it at any position withlayer.sample(p). AcolorEffectshader only gets the color of the pixel it is drawing. AlayerEffectshader can also read that pixel's neighbors, which is what blur, convolution, edge detection, distortion and edge-preserving filters need.
What does layerEffect add over colorEffect?
Chapter 1 listed the three shader modifiers SwiftUI offers. Until now you have mostly used two of them:
colorEffecthands your function one pixel's position and color, and you return a new color. It can't look at any other pixel.distortionEffecthands you a position, and you return the position SwiftUI should read from instead. You choose where to read, but you get one read per pixel and you can't change the color.
layerEffect lifts both limits. SwiftUI renders the view into an offscreen image (the layer) and passes that layer to your shader. Your function decides which positions to read, how many reads to make, and how to combine them:
#include <metal_stdlib>
#include <SwiftUI/SwiftUI_Metal.h> // defines SwiftUI::Layer
using namespace metal;
[[ stitchable ]] half4 myEffect(float2 position, SwiftUI::Layer layer) {
half4 here = layer.sample(position); // the pixel being drawn
half4 right = layer.sample(position + float2(1.0, 0.0)); // one point to the right
return (here + right) * 0.5; // average of the two
}
The first two parameters are fixed: position (where this pixel is) and layer (the rendered view). Anything after them is yours, passed from Swift. Without the SwiftUI_Metal.h include, the compiler doesn't know what SwiftUI::Layer is.
If a shader only ever calls layer.sample(position), it does nothing a colorEffect couldn't do, because a colorEffect already receives that color as its color argument. The interesting layerEffect shaders read other positions, and that's what the rest of this chapter is about.
On the Swift side, every shader in this chapter is applied the same way. This is the pencilSketch shader from the Xcode project's Chapter10 folder:
Image(.geoUnsplash)
.resizable()
.scaledToFit()
.visualEffect { content, proxy in
content.layerEffect(
ShaderLibrary.pencilSketch(
.float2(proxy.size.width, proxy.size.height), // the view size, passed by you
.float(0.6)
),
maxSampleOffset: CGSize(width: 1, height: 1) // reads at most 1 point away
)
}
Three things to notice:
positionis in points, in the view's local coordinate space: origin at the top-left, y growing downward.- The shader is not told the view's size. Most shaders here take a
float2 sizeargument, and you supply it from theGeometryProxythat.visualEffectgives you. The project'sMetalCanvasViewpasses your closure straight to.visualEffect, which is why every example closure receivescontent, proxy. layerEffectneeds amaxSampleOffset. The next section explains what it means and how to pick it.
What does maxSampleOffset do?
maxSampleOffset is a promise about how far from position your shader reads. Apple's documentation puts it this way: if the shader samples the layer at locations other than the destination position, this value must give the maximum sampling distance on each axis. SwiftUI uses it to decide how much surrounding content has to be in the layer so that the pixels you ask for actually exist.
You work it out by reading your own shader. Find the largest offset you ever add to position, separately for x and y, in points:
- 3×3 convolution: the loops add offsets of −1, 0 and +1 on each axis, so the answer is
CGSize(width: 1, height: 1). That's exactly what the project'sConvolutionViewpasses. - Chromatic distortion (later in this chapter): the wave offset is
sin(...) * distortionAmount * 20on x andcos(...) * distortionAmount * 20on y. Sine and cosine stay between −1 and 1, so atdistortionAmount = 1that's up to 20 points on each axis. The red and blue reads then add another 2 points on x. The total isCGSize(width: 22, height: 20). - Horizontal Gaussian blur with
radius = 4: it reads3 × 4 = 12points left and right and nothing vertically, soCGSize(width: 12, height: 0). - A filter that only reads
layer.sample(position): nothing beyond the pixel itself, so.zero.
Getting it wrong doesn't produce an error. If the value is too small, reads that go past the content SwiftUI prepared are clamped to the edge of the layer (see the next section), so you can get smeared or missing pixels, most visibly near the view's edges. If it's too large, the effect still works; SwiftUI just prepares more surrounding content than you use. When a parameter changes how far you read, such as a blur radius, compute the offset from that parameter instead of hard-coding it.
What is a texture, and how does layer.sample read it?
A texture is a grid of pixels, but in a shader it helps to think of it as a function that maps a position to a color:
texture: (u, v) → (r, g, b, a)
The input doesn't have to land on a pixel center. You can ask for the color at any position, including halfway between two pixels.
The whole SwiftUI::Layer API
Apple documents SwiftUI::Layer like this:
namespace SwiftUI {
struct Layer {
half4 sample(float2 position) const;
};
}
That is the entire API: one function with one argument. There is no sampler parameter, so you can't choose the filtering mode, the edge behavior or a mipmap level. If you open SwiftUI_Metal.h in the Xcode SDK, you can see what sample() does with your position:
- It converts the position from points in your view's coordinate space to the layer texture's own coordinates.
- It clamps that coordinate to the layer's region. Reading far outside the view never crashes and never returns random memory. You get the color at the nearest edge of the layer.
- It reads the texture with linear filtering.
Linear filtering, with numbers
Linear filtering means that a position between pixel centers returns a weighted average of the nearest pixels: up to four of them in 2D, two along a single row. Take two neighboring pixels in a row, a red one (1, 0, 0) and a blue one (0, 0, 1):
- Sampling exactly at the red pixel's center returns
(1, 0, 0). - Halfway between the two centers returns
(0.5, 0, 0.5). - A quarter of the way from red to blue returns 75% red and 25% blue,
(0.75, 0, 0.25).
This is why distortions and zooms look smooth instead of blocky. If you want the blocky look (nearest-neighbor sampling), snap the position to the center of a cell before you sample, as in floor(position / cell) * cell + cell * 0.5. Every point inside a cell then reads the same color. The pixelate challenge at the end of this chapter uses exactly this trick.
Repeat and mirror modes aren't built in either. If you want the image to tile, wrap the position yourself (for example with fmod) before sampling.
Colors come back premultiplied
layer.sample() returns premultiplied alpha: the red, green and blue values have already been multiplied by alpha. A fully opaque white pixel is (1, 1, 1, 1). The same white at 50% opacity is (0.5, 0.5, 0.5, 0.5), not (1, 1, 1, 0.5). Averaging premultiplied colors is the correct way to blur: a fully transparent pixel is (0, 0, 0, 0) and adds nothing to the average. Color adjustments need more care, which the pitfalls section covers.
Points versus pixels
position is in points. On a 3× iPhone display, one point spans three physical pixels in each direction. So when a shader in this chapter reads "the pixel to the right" with float2(1.0, 0.0), it's really reading one point to the right. For most effects that's fine. If you need to step by exactly one physical pixel, pass the display scale (@Environment(\.displayScale)) as an argument and step by 1.0 / displayScale.
You'll also see this pattern in several shaders below and in the Xcode project:
float2 texelSize = 1.0 / size;
// ...
layer.sample(position + float2(x, y) * texelSize * size);
texelSize * size is (1 / size) * size, which is 1. The two cancel, and the offset is simply float2(x, y) points. It's harmless, but it isn't converting anything.
What are the four core texture operations?
1. Convolution: weighted sums of neighbors
Convolution slides a small grid of weights, called the kernel, across the image. For each output pixel, you center the kernel on that pixel, multiply each neighbor by the weight sitting on top of it, and add up the products. The sum is the new value for that pixel.
Original pixels: Kernel: Result:
[40][80][120] [-1][0][1]
[50][90][130] × [-2][0][2] = One new pixel value
[60][100][140] [-1][0][1]
Here is that sum worked out. The numbers are brightness on a 0 to 255 scale, and the kernel is Sobel X, an edge detector:
top row: -1×40 + 0×80 + 1×120 = 80
middle row: -2×50 + 0×90 + 2×130 = 160
bottom row: -1×60 + 0×100 + 1×140 = 80
-----
new value for the center pixel 320
The neighborhood gets brighter from left to right, so Sobel X produces a large positive number (320, or about 1.25 on the shader's 0 to 1 scale). On a flat patch where all nine pixels are equal, the negative and positive weights cancel and the result is 0. That's how an edge detector works: it responds to change and ignores uniform areas.
Run the same nine pixels through the Gaussian blur kernel listed below and you get (40 + 2×80 + 120 + 2×50 + 4×90 + 2×130 + 60 + 2×100 + 140) / 16 = 1440 / 16 = 90. That equals the center value, because a smooth ramp averages out to its middle. On a noisy patch, the same kernel pulls an outlier toward its neighbors, which is what blurring is.
A few ways to read a kernel:
- Blur: positive weights spread over the neighborhood, so each pixel becomes an average.
- Sharpen: a large positive center and negative neighbors, so differences between a pixel and its surroundings get exaggerated.
- Edge detection: weights that cancel out on flat areas, so only changes survive.
In the shader below, the loops run y from −1 to 1 on the outside and x from −1 to 1 on the inside. So kernel0 is the top-left weight, kernel4 the center and kernel8 the bottom-right. Remember that y grows downward, so y = -1 is the row above.
3x3 Convolution Filter
Interactive convolution filter with predefined kernels and visual matrix editor
Gaussian blur - smooths the image by averaging nearby pixels
In the Xcode project, ConvolutionView drives the same shader with five presets (identity, blur, sharpen, edge detect and emboss) and lets you type in your own nine values. The project's pencilSketch shader is the edge detector in practice: it runs Sobel X and its vertical twin, Sobel Y, adds the lengths of the two results, and inverts the output so edges are dark lines on white.
Common kernels:
// Edge detection (Sobel X)
float sobelX[9] = {
-1, 0, 1,
-2, 0, 2,
-1, 0, 1
};
// Gaussian blur
float gaussian[9] = {
1/16.0, 2/16.0, 1/16.0,
2/16.0, 4/16.0, 2/16.0,
1/16.0, 2/16.0, 1/16.0
};
// Sharpen
float sharpen[9] = {
0, -1, 0,
-1, 5, -1,
0, -1, 0
};
The sum of a kernel's weights tells you what happens to flat areas of the image:
- Sum of 1: flat areas keep their brightness. The Gaussian (16/16), the sharpen kernel (5 − 4) and the project's emboss preset all sum to 1. Sharpen still changes the image a lot; it just doesn't change the average brightness.
- Sum of 0: flat areas go to black and only changes survive. Sobel X and the project's edge-detect preset (8 − 8) sum to 0.
- Sum above 1 brightens the whole image; below 1 darkens it.
- Negative results: Sobel X gives −320 on a ramp that gets darker from left to right. A color channel can't display a negative value, so those edges end up black. To catch edges in both directions, take
abs()of the result, or combine X and Y withlength()the waypencilSketchdoes.
2. Separable filters: two cheap passes instead of one expensive one
Some 2D kernels are just a 1D kernel multiplied by itself. The 3×3 Gaussian is one of them:
[1] [1 2 1]
[2] × [1 2 1] = [2 4 2] (then divide by 16)
[1] [1 2 1]
So you can blur each row with [1 2 1] / 4, then blur the result's columns with [1 2 1] / 4, and get exactly the same image as the 3×3 kernel divided by 16. For a 3×3 kernel that's 3 + 3 = 6 reads per pixel instead of 9. The saving grows fast: a 13-tap Gaussian needs 13 + 13 = 26 reads as two passes, against 13 × 13 = 169 as a single 2D pass.
In the code below, radius acts as the Gaussian's spread (its sigma), and the loop reads 3 × radius points on each side, because the weights beyond that are negligible. With radius = 2 the loop runs from −6 to 6, 13 reads, with weights exp(-i² / 8):
i: 0 ±1 ±2 ±3 ±4 ±5 ±6
weight: 1.000 0.882 0.607 0.325 0.135 0.044 0.011
These weights add up to about 5.0, not 1, which is why the function divides by weightSum at the end. Without that, the image would come out five times too bright.
Separable Gaussian Blur
Efficient blur implementation using separable filters - demonstrates the power of optimized texture sampling
// Instead of 9 samples for 3x3 blur...
// Do 3 samples horizontal, then 3 samples vertical = 6 total!
[[ stitchable ]] half4 gaussianBlurHorizontal(
float2 position,
SwiftUI::Layer layer,
float2 size,
float radius
) {
float2 texelSize = float2(1.0 / size.x, 0.0);
half4 result = half4(0.0);
float weightSum = 0.0;
// Gaussian weights
int samples = int(radius * 3.0);
for (int i = -samples; i <= samples; i++) {
float weight = exp(-float(i * i) / (2.0 * radius * radius));
result += layer.sample(position + float(i) * texelSize * size) * weight;
weightSum += weight;
}
return result / weightSum;
}
[[ stitchable ]] half4 gaussianBlurVertical(
float2 position,
SwiftUI::Layer layer,
float2 size,
float radius
) {
// Same as horizontal, but stepping along the Y axis
float2 texelSize = float2(0.0, 1.0 / size.y);
half4 result = half4(0.0);
float weightSum = 0.0;
int samples = int(radius * 3.0);
for (int i = -samples; i <= samples; i++) {
float weight = exp(-float(i * i) / (2.0 * radius * radius));
result += layer.sample(position + float(i) * texelSize * size) * weight;
weightSum += weight;
}
return result / weightSum;
}The second pass has to read the output of the first. In SwiftUI you get that by applying two layerEffect modifiers in a row. Each modifier renders the view as it looks after the modifiers before it, so the vertical pass sees the horizontally blurred image:
struct BlurredPhoto: View {
let radius: Float = 4
var body: some View {
Image(.geoUnsplash)
.resizable()
.scaledToFit()
.visualEffect { [radius] content, proxy in // capture the value; the closure is @Sendable
content
.layerEffect(
ShaderLibrary.gaussianBlurHorizontal(.float2(proxy.size), .float(radius)),
maxSampleOffset: CGSize(width: CGFloat(radius * 3), height: 0)
)
.layerEffect(
ShaderLibrary.gaussianBlurVertical(.float2(proxy.size), .float(radius)),
maxSampleOffset: CGSize(width: 0, height: CGFloat(radius * 3))
)
}
}
}
Each pass declares its reach only along the axis it reads.
3. Non-linear filters: decisions instead of sums
Convolution is linear: every output pixel is a fixed weighted sum of its neighbors. A non-linear filter makes a decision based on what it finds, such as counting, sorting or picking a winner. The oil painting filter below works like this for each pixel:
- Split brightness (0 to 1) into
levelsbins. Withlevels = 4, the bins cover 0 to 0.25, 0.25 to 0.5, 0.5 to 0.75 and 0.75 to 1. - Visit every neighbor within
radiuspoints. Compute its brightness withdot(rgb, (0.299, 0.587, 0.114)), which weights green most because our eyes are most sensitive to it. Add 1 to that bin's count and add the neighbor's color to that bin's color total. - Find the bin with the most pixels and output the average color of the pixels in it.
Small details lose the vote to the dominant tone around them, so the image breaks into flat patches that look like brush strokes. The cost grows with the square of the radius: radius = 3 means a 7 × 7 neighborhood, 49 reads per pixel.
Metal has no dynamic arrays, so the histogram is a fixed array of 8 entries. The code clamps levels to 8 so a larger value can't write past the end of it.
Oil Painting Effect
Non-linear filter that creates painterly effects by finding dominant colors in local neighborhoods
[[ stitchable ]] half4 oilPainting(
float2 position,
SwiftUI::Layer layer,
float2 size,
float radius,
float levels
) {
float2 texelSize = 1.0 / size;
// Discretize the color space
int levelCount = clamp(int(levels), 1, 8);
float levelSize = 1.0 / levels;
// Histogram for each discretized color level
float histogram[8]; // Fixed size: Metal has no dynamic arrays
half3 colorSum[8];
// Initialize
for (int i = 0; i < levelCount; i++) {
histogram[i] = 0.0;
colorSum[i] = half3(0.0);
}
// Sample neighborhood
int radiusInt = int(radius);
for (int y = -radiusInt; y <= radiusInt; y++) {
for (int x = -radiusInt; x <= radiusInt; x++) {
float2 offset = float2(x, y) * texelSize;
half4 sample = layer.sample(position + offset * size);
// Discretize intensity
float intensity = dot(sample.rgb, half3(0.299, 0.587, 0.114));
int level = int(intensity * levels);
level = clamp(level, 0, levelCount - 1);
// Add to histogram
histogram[level] += 1.0;
colorSum[level] += sample.rgb;
}
}
// Find dominant intensity level
int maxLevel = 0;
float maxCount = 0.0;
for (int i = 0; i < levelCount; i++) {
if (histogram[i] > maxCount) {
maxCount = histogram[i];
maxLevel = i;
}
}
// Return average color of dominant level
half3 finalColor = colorSum[maxLevel] / histogram[maxLevel];
return half4(finalColor, layer.sample(position).a);
}The Xcode project has a variant of this filter called oilPaintingFilter. It always uses 8 bins, takes brushSize (the radius) and intensity as arguments, clamps its read positions to the view's bounds, and finishes with mix(original, result, intensity) so you can dial the effect in gradually.
4. Distortion: computing where to read
A distortion shader first calculates a position, then reads from it. With layerEffect you can read several times from slightly different positions, which distortionEffect can't do because it returns a single position per pixel.
chromaticDistortion does both. It builds a wave offset from sin and cos of the normalized position plus time, scales it by distortionAmount * 20 points, and then reads three times: red from 2 points to the right of the distorted position, green from the position itself, and blue from 2 points to the left. Splitting the channels like this imitates chromatic aberration, the colored fringes a cheap lens produces because it bends red and blue light by different amounts. The maxSampleOffset section above works out how far this shader reads.
Chromatic Distortion
Combines spatial distortion with chromatic aberration for dramatic visual effects
[[ stitchable ]] half4 chromaticDistortion(
float2 position,
SwiftUI::Layer layer,
float2 size,
float time,
float distortionAmount
) {
float2 uv = position / size;
// Create distortion pattern
float2 distortion = float2(
sin(uv.y * 20.0 + time * 2.0),
cos(uv.x * 20.0 - time * 1.5)
) * distortionAmount;
// Sample from distorted position
float2 distortedPos = position + distortion * 20.0;
// Add chromatic aberration
half4 r = layer.sample(distortedPos + float2(2.0, 0.0));
half4 g = layer.sample(distortedPos);
half4 b = layer.sample(distortedPos - float2(2.0, 0.0));
return half4(r.r, g.g, b.b, g.a);
}Smart blur: averaging only similar colors
A regular blur averages every neighbor, so it softens edges along with noise. The smart blur adds one test: a neighbor only joins the average if its color is close to the center pixel's color. The if (colorDiff < threshold) line does that. Color distance is measured as the length of the difference between the two RGB values.
Here is the test with numbers. Say the center pixel is sky blue, (0.2, 0.4, 0.8), and threshold is 0.3:
- A neighbor that is also sky,
(0.25, 0.45, 0.8), differs by(0.05, 0.05, 0). Its length is about 0.07, under the threshold, so it's included. - A neighbor that is a leaf,
(0.2, 0.6, 0.2), differs by(0, 0.2, −0.6). Its length is about 0.63, over the threshold, so it's skipped.
Included neighbors are weighted by exp(-dist / radius), so closer ones count more. With radius = 4, a neighbor 2 points away gets weight exp(-0.5) ≈ 0.61. The result is that variations inside the sky get smoothed, but sky never bleeds into the trees. That makes it useful for reducing noise, smoothing skin without blurring the eyes, and cleaning up compression artifacts.
The loop visits a (2 × radius + 1)² square of neighbors. The project's SmartBlurView slider goes up to 50, which is 101 × 101 = 10,201 iterations for every pixel, so keep an eye on the radius.
Smart Blur (Edge-Preserving)
Intelligent blur that preserves edges while smoothing similar colors - perfect for noise reduction
[[ stitchable ]] half4 smartBlur(
float2 position,
SwiftUI::Layer layer,
float2 size,
float radius,
float threshold
) {
half4 center = layer.sample(position);
half4 result = center;
float totalWeight = 1.0;
int samples = int(radius);
for (int y = -samples; y <= samples; y++) {
for (int x = -samples; x <= samples; x++) {
if (x == 0 && y == 0) continue;
float2 offset = float2(x, y);
float dist = length(offset);
if (dist > radius) continue;
half4 sample = layer.sample(position + offset);
// Compare similarity
float colorDiff = length(sample.rgb - center.rgb);
// Only include similar pixels
if (colorDiff < threshold) {
float weight = exp(-dist / radius);
result += sample * weight;
totalWeight += weight;
}
}
}
return result / totalWeight;
}How do you build Instagram-style filters in SwiftUI?
A photo filter is a chain of small adjustments applied in a fixed order. vintageFilter runs five of them on each pixel:
- Color grading. It computes the pixel's brightness (luminance), then blends from a bluish shadow color to a warm midtone as luminance goes from 0 to 0.5, and from the midtone to a slightly yellow highlight as it goes from 0.5 to 1. The graded color replaces 70% of the original.
- Lower contrast.
mix(half3(0.5), color.rgb, 0.85)pulls every channel 15% of the way toward middle gray. - Vignette.
length(uv - 0.5)is the distance from the center in normalized coordinates: 0 in the middle, about 0.71 in the corners.smoothstep(0.2, 0.8, ...)turns that into a darkening factor that starts a little way out from the center. Becauseuvis position divided by size, the vignette stretches into an oval on non-square views. ThecinematicLookchallenge solution corrects for this by scaling y bysize.y / size.x. - Film grain. A hash of the position gives a pseudo-random value per pixel (the hash from Chapter 6), shifted to the −0.5 to 0.5 range and added to all three channels.
- Fade. Mixing a little toward white lifts the blacks, the washed-out look of old prints.
This shader only ever reads layer.sample(position), so it could also be written as a colorEffect, and its maxSampleOffset could be .zero.
Instagram-Style Vintage Filter
Professional photo filter combining color grading, vignetting, film grain, and lifted blacks
[[ stitchable ]] half4 vintageFilter(
float2 position,
SwiftUI::Layer layer,
float2 size,
float vignette,
float grainAmount,
float fadeAmount
) {
float2 uv = position / size;
half4 color = layer.sample(position);
// 1. Color grading - vintage tone
half3 shadows = half3(0.1, 0.05, 0.15); // Blue shadows
half3 midtones = half3(1.0, 0.95, 0.85); // Warm mids
half3 highlights = half3(1.0, 0.98, 0.95); // Slight yellow
float luminance = dot(color.rgb, half3(0.299, 0.587, 0.114));
half3 graded = mix(shadows, midtones, smoothstep(0.0, 0.5, luminance));
graded = mix(graded, highlights, smoothstep(0.5, 1.0, luminance));
color.rgb = mix(color.rgb, graded, 0.7);
// 2. Reduced contrast
color.rgb = mix(half3(0.5), color.rgb, 0.85);
// 3. Vignette
float2 vignetteUV = uv - 0.5;
float vignetteIntensity = smoothstep(0.2, 0.8, length(vignetteUV));
color.rgb *= 1.0 - vignetteIntensity * vignette;
// 4. Film grain
float grain = fract(sin(dot(uv * 1000.0, float2(12.9898, 78.233))) * 43758.5453);
grain = (grain - 0.5) * grainAmount;
color.rgb += half3(grain);
// 5. Fade (lifted blacks)
color.rgb = mix(color.rgb, half3(1.0), fadeAmount * 0.1);
return color;
}Steps 4 and 5 add to the color channels regardless of alpha. On an opaque photo that's fine. On a view with transparent areas it breaks the premultiplied-alpha rule; see the pitfalls section.
Can you do multi-pass shaders in SwiftUI?
Partly. Some effects need the finished output of one step before the next step can run. Bloom (the glow around bright lights) is the classic case:
- Extract the bright areas.
- Blur them.
- Add the blurred glow back onto the original image.
Steps 1 and 2 work in SwiftUI, because you can chain layerEffect modifiers, as in the separable blur above. Each one reads the output of the one before.
Step 3 is the problem. A layerEffect shader receives exactly one SwiftUI::Layer, so no single shader can read both the original image and the blurred glow. You can still do the combine in SwiftUI, just outside the shader: stack the original and the processed copy in a ZStack and let a blend mode add them together.
ZStack {
Image(.geoUnsplash)
.resizable()
.scaledToFit()
Image(.geoUnsplash)
.resizable()
.scaledToFit()
.visualEffect { content, proxy in
content
.layerEffect(
ShaderLibrary.bloomExtract(.float2(proxy.size), .float(0.7)),
maxSampleOffset: .zero
)
.layerEffect(
ShaderLibrary.gaussianBlurHorizontal(.float2(proxy.size), .float(4)),
maxSampleOffset: CGSize(width: 12, height: 0)
)
.layerEffect(
ShaderLibrary.gaussianBlurVertical(.float2(proxy.size), .float(4)),
maxSampleOffset: CGSize(width: 0, height: 12)
)
}
.blendMode(.plusLighter) // adds the glow on top of the original
}
.plusLighter adds the two images and clips at white. The bloomCombine function in the preview below also tone-maps the sum so bright areas don't clip, and that function needs two layers at once. Pipelines like that, or ones that need intermediate textures or the previous frame, require driving Metal yourself: an MTKView with your own render passes, where pass 1 renders into texture A, pass 2 reads A and renders into texture B, and a final pass combines the original with B. This course doesn't cover that.
bloomExtract uses a soft threshold. Instead of a hard cut, smoothstep(threshold - 0.1, threshold + 0.1, brightness) fades pixels in over a 0.2-wide band of brightness. Multiplying the whole premultiplied color by that factor keeps the result valid and makes dark pixels fully transparent, so they add nothing in the final blend.
Bloom Extraction (Multi-Pass Demo)
First pass of bloom effect - extracts bright areas with smooth threshold for glowing highlights
// Pass 1: Extract bright areas
[[ stitchable ]] half4 bloomExtract(
float2 position,
SwiftUI::Layer layer,
float2 size,
float threshold
) {
half4 color = layer.sample(position);
float brightness = dot(color.rgb, half3(0.299, 0.587, 0.114));
// Soft knee: fade in over threshold +/- softness instead of a hard cut
float softness = 0.1;
float response = smoothstep(threshold - softness, threshold + softness, brightness);
// Scale the whole premultiplied color: dark pixels become fully transparent
return color * response;
}
// Pass 2: Blur the bright areas (use separable blur)
// Pass 3: Combine with original
// Needs two layers, so it can't be called from SwiftUI's layerEffect
// (one layer per shader). Use it in a Metal render pass, or combine
// in SwiftUI with .blendMode(.plusLighter) instead.
[[ stitchable ]] half4 bloomCombine(
float2 position,
SwiftUI::Layer original,
SwiftUI::Layer bloom,
float2 size,
float intensity
) {
half4 originalColor = original.sample(position);
half4 bloomColor = bloom.sample(position);
// Additive blending
half3 result = originalColor.rgb + bloomColor.rgb * intensity;
// Tone mapping to prevent over-bright
result = result / (1.0 + result);
return half4(result, originalColor.a);
}How do you blur an image while preserving edges?
Use a bilateral filter. It's the smooth version of the smart blur: instead of a yes/no color test, every neighbor gets two weights, and they're multiplied.
- Spatial weight, from distance:
exp(dist² × spatialFactor), wherespatialFactor = -0.5 / spatialSigma². This is an ordinary Gaussian blur weight. - Intensity weight, from color difference:
exp(colorDiff² × intensityFactor), whereintensityFactor = -0.5 / intensitySigma².
With the project's default values, spatialSigma = 5 and intensitySigma = 0.1:
spatialFactor = -0.5 / 25 = -0.02
intensityFactor = -0.5 / 0.01 = -50
neighbor 3 points away: exp(9 × -0.02) = 0.84
neighbor 8 points away: exp(64 × -0.02) = 0.28
color differs by 0.05: exp(0.0025 × -50) = 0.88
color differs by 0.3: exp(0.09 × -50) = 0.011
A neighbor 3 points away with a similar color gets 0.84 × 0.88 ≈ 0.74. The same neighbor across an edge, with a color 0.3 away, gets 0.84 × 0.011 ≈ 0.009, almost nothing. Because the falloff is smooth, there's no visible seam where colors cross a threshold, which can happen with the smart blur.
People use it for noise reduction that keeps detail, skin smoothing ("beauty filters") and as a clean-up step before other image processing.
The shader limits the radius to min(spatialSigma × 2, 10) points, so it never reads more than a 21 × 21 square (441 iterations), and it skips neighbors whose spatial weight is below 0.01. Keep spatialSigma above 0: at 0, spatialFactor divides by zero and the output turns into NaN.
Bilateral Filter (Professional Edge-Aware)
Advanced edge-preserving filter used in professional photo editing - smooths while maintaining sharp edges
[[ stitchable ]] half4 bilateralFilter(
float2 position,
SwiftUI::Layer layer,
float2 size,
float spatialSigma,
float intensitySigma
) {
half4 center = layer.sample(position);
half4 result = half4(0.0);
float totalWeight = 0.0;
// Reduce radius for performance
int radius = int(min(spatialSigma * 2.0, 10.0));
// Precompute constants
float spatialFactor = -0.5 / (spatialSigma * spatialSigma);
float intensityFactor = -0.5 / (intensitySigma * intensitySigma);
for (int y = -radius; y <= radius; y++) {
for (int x = -radius; x <= radius; x++) {
float2 offset = float2(x, y);
// Spatial weight (precomputed factor)
float spatialDist2 = float(x * x + y * y);
float spatialWeight = exp(spatialDist2 * spatialFactor);
// Skip negligible weights
if (spatialWeight < 0.01) continue;
// Sample neighbor
half4 sample = layer.sample(position + offset);
// Intensity weight
half3 colorDiff = sample.rgb - center.rgb;
float intensityDist2 = dot(colorDiff, colorDiff);
float intensityWeight = exp(intensityDist2 * intensityFactor);
// Combined weight
float weight = spatialWeight * intensityWeight;
result += sample * weight;
totalWeight += weight;
}
}
return result / totalWeight;
}How do you optimize texture shaders for performance?
1. Minimize texture samples
Most of the cost of these shaders is in the reads, and a 2D loop's read count grows with the square of its radius. Three ways to cut it:
- Split the filter into two 1D passes when the kernel is separable (see above).
- Skip neighbors whose weight is negligible, as the bilateral filter does.
- Let linear filtering average pixels for you. A read placed exactly between two pixel centers returns their average in one read; a read at the corner where four pixels meet returns the average of all four.
The last trick is shown below. It only lines up with real pixels if your offsets are in pixels, and position is in points. On a 2× or 3× display you would need to pass the display scale and convert.
// EXPENSIVE: 25 samples for 5x5 blur
for (int y = -2; y <= 2; y++) {
for (int x = -2; x <= 2; x++) {
// 25 texture reads!
}
}
// CHEAPER: let linear filtering average a 2x2 block per read
// Each read lands where four pixels meet (assumes 1 point = 1 pixel)
float2 texelSize = 1.0 / size;
half4 tl = layer.sample(position + float2(-1.5, -1.5) * texelSize * size);
half4 tr = layer.sample(position + float2( 1.5, -1.5) * texelSize * size);
half4 bl = layer.sample(position + float2(-1.5, 1.5) * texelSize * size);
half4 br = layer.sample(position + float2( 1.5, 1.5) * texelSize * size);
// 4 reads covering a 4x4 area: an approximation of the 5x5 box, not an exact match
2. Cache calculations
exp() inside a loop runs once per neighbor per pixel. If the weights don't depend on the pixel, compute them once. The five weights below are the binomial numbers 1, 4, 6, 4, 1 divided by 16, a close approximation of a Gaussian that sums to exactly 1. To share a table across functions, declare it at file scope as constant float weights[5] = { ... }; (Metal requires the constant address space there).
// EXPENSIVE: Recalculate for every pixel
float gaussian(float x, float sigma) {
return exp(-x * x / (2.0 * sigma * sigma));
}
// OPTIMIZED: Pre-calculate weights
const float weights[5] = {0.0625, 0.25, 0.375, 0.25, 0.0625}; // Gaussian approximation
3. Work in one coordinate system
layer.sample() takes points, so offsets in points can be added directly. Converting to UV and back costs instructions and adds nothing. The texelSize * size pattern in this chapter's shaders is an example of that round trip.
// WRONG: Converting back and forth
float2 uv = position / size;
float2 samplePos = uv * size; // Redundant!
// CORRECT: Work in one coordinate system
float2 offset = float2(1.0, 0.0); // In points, like position
half4 neighbor = layer.sample(position + offset);
What are the common layerEffect pitfalls?
Pitfall 1: Sampling past the view's edges
layer.sample() clamps every position to the layer's region, so a far-off read can't crash or return garbage memory. What you get is the color at the nearest edge of the layer, and outside the view itself there is no content, so blurs and distortions tend to fade or smear near the borders. If you'd rather repeat the view's own edge pixels, clamp the position to the view's bounds yourself before sampling, as the project's oilPaintingFilter does.
// Reads far outside the view: sample() clamps to the edge of the layer,
// so you get edge or empty pixels, never a crash
half4 sample = layer.sample(position + float2(1000.0, 1000.0));
// Edge-extend: clamp to the view's own bounds first
float2 samplePos = clamp(position + offset, float2(0.0), size);
half4 sample = layer.sample(samplePos);
Pitfall 2: Forgetting premultiplied alpha
Remember that colors from layer.sample() are premultiplied, so 50% transparent white is (0.5, 0.5, 0.5, 0.5). Two kinds of maths go wrong if you forget this.
Combining two colors: adding them directly can push alpha above 1. To put one premultiplied color on top of another, use the "over" formula: the top color plus the bottom color scaled by how much the top lets through.
// WRONG: Color math without considering alpha
half4 result = color1 + color2;
// CORRECT: Handle premultiplied alpha properly
half4 result;
result.rgb = color1.rgb + color2.rgb * (1.0 - color1.a);
result.a = color1.a + color2.a * (1.0 - color1.a);
Color adjustments: a curve like pow() or a tint expects the real color, not the color already darkened by alpha. And adding something to the RGB channels of a transparent pixel, as the vintage filter's grain does, produces RGB values bigger than alpha. That isn't a valid premultiplied color, and it shows up as a bright glow over areas that should be transparent. For views with transparency, un-premultiply, adjust, then premultiply again:
half4 c = layer.sample(position);
half3 rgb = c.a > 0.0h ? c.rgb / c.a : half3(0.0); // undo premultiplication
rgb = pow(rgb, half3(0.8)); // any color adjustment
return half4(rgb * c.a, c.a); // premultiply again
Pitfall 3: Weights that don't sum to 1
// WRONG: Weights don't sum to 1.0
half4 blurred = sample1 * 0.3 + sample2 * 0.3 + sample3 * 0.3;
// Result is 90% intensity!
// CORRECT: Normalize weights
float totalWeight = 0.3 + 0.3 + 0.3;
half4 blurred = (sample1 * 0.3 + sample2 * 0.3 + sample3 * 0.3) / totalWeight;
This is why every blur in this chapter keeps a running weightSum or totalWeight and divides by it at the end.
What makes a photo filter look polished?
The algorithms in this chapter are standard. What makes the result look good is mostly in how you apply them:
- Order matters. Each step works on the output of the step before. The vintage filter adds grain after the vignette, so the grain stays visible in the dark corners. If you sharpened after adding grain, you would sharpen the grain too.
- Avoid clipping. Any channel above 1 shows as flat white and loses detail.
bloomCombinetone-maps withresult / (1.0 + result), which maps 1 to 0.5 and 3 to 0.75 and never reaches 1. ThecinematicLooksolution rolls highlights off above a luminance of 0.7. - Blend with the original.
mix(original, result, intensity), used byoilPaintingFilterandcinematicLook, gives you a strength slider and makes heavy effects usable at lower settings. - Test with the largest settings on a real device. Read counts grow with the square of the radius, so a slider that's fine at 5 can be far too slow at 50.
Challenges
Challenge 1: Comic Book Effect

Create a comicBook shader that turns photos into comic-style art using edge detection and posterization.
The solution takes size, colorLevels, edgeThreshold and halftoneSize.
Requirements:
- Detect edges and draw them as black lines (Sobel X and Y on the brightness of the 8 neighbors; compare the edge strength to
edgeThreshold) - Reduce each color channel to a few levels (posterization:
floor(rgb * levels) / levels; the solution's slider runs from 3 to 8) - Add halftone dots in dark areas: divide the view into cells
halftoneSizepoints wide and draw a dot in each cell that gets bigger as the area gets darker - Keep the effect clean and readable
Challenge 2: Pixelate Transition

Create a pixelateReveal shader that reveals or hides content by progressively changing the pixel size.
The solution takes size, progress (0 is fully pixelated, 1 is full resolution), maxPixelSize and popEffect.
Requirements:
- Start with large pixels (heavily pixelated)
- Smoothly transition to normal resolution
- Pixels should "pop in" rather than just shrink. A random value per block (a hash of the block's position) lets each block appear at a slightly different moment.
- Work well as a transition effect
Hint: this is the nearest-neighbor trick from earlier. Snap position to the center of its block and sample there, so the whole block reads one color. The block's center can be up to half a block away from position (and the solution's pop animation reads up to a full block away), so set maxSampleOffset from maxPixelSize.
Challenge 3: Heat Haze

Create a heatHaze shader that simulates the wavy distortion seen above hot surfaces.
The solution takes size, time, intensity and riseSpeed.
Requirements:
- Wavy distortion, mostly sideways, with waves that travel upward
- Distortion should animate and flow upward over time
- Stronger effect at the bottom, fading toward the top. Remember that y grows downward, so the bottom of the view is
uv.y = 1. - Subtle chromatic aberration for realism
Hint: layer two or three sine waves of different frequencies for a less regular shimmer. For time, use seconds elapsed since the view appeared (for example from a TimelineView(.animation) and a start date), not the raw Date().timeIntervalSinceReferenceDate, which is too large a number for a Float to animate smoothly.
Challenge 4: Cinematic Color Grading

Create a cinematicLook shader that applies the teal-and-orange color grading common in films and social media.
The solution takes size, intensity, warmth, contrast, grain, highlightProtection, shadowLift and splitTone.
Requirements:
- Teal highlights and orange shadows (split toning, with strength set by
splitTone) - S-curve contrast enhancement for a more dramatic look
- Highlight roll-off to prevent blown-out whites
- Fine film grain for texture
- Subtle vignette for focus
- Color temperature control for warmth/coolness
- A final
mixwith the original, controlled byintensity
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
Check your understanding before moving on:
- What's the difference between linear and nearest neighbor sampling, and when would you use each?
Linear sampling blends the pixels around the requested position, so results look smooth but fine detail softens. Nearest-neighbor sampling returns the single closest pixel, which keeps hard edges but looks blocky when scaled. Linear suits blurs, zooms and distortions; nearest-neighbor suits pixel art and pixelation effects. In SwiftUI, layer.sample() always uses linear filtering and has no sampler parameter. To get the nearest-neighbor look, snap the position to the center of a cell before sampling.
- Why are separable filters more efficient than non-separable ones?
A separable 2D kernel equals a 1D kernel applied horizontally and then vertically. A 5×5 kernel needs 25 reads per pixel in one pass, but only 5 + 5 = 10 as two 1D passes. In general the cost drops from n² reads to 2n. In SwiftUI you run the two passes as two chained layerEffect modifiers.
- How do you handle edge cases when sampling outside texture boundaries?
layer.sample() already clamps positions to the layer, so out-of-range reads return edge pixels rather than crashing. Past the view's own bounds there's no content, so if you want the view's edge pixels repeated, clamp the position yourself: clamp(samplePos, float2(0.0), size). Wrapping (tiling) and mirroring aren't built in; you implement them by transforming the position before you sample. Which one is right depends on the look you want.
- What's the importance of normalizing kernel weights in convolution?
The sum of the weights scales the brightness of flat areas. A sum of 1 keeps brightness unchanged, above 1 brightens and below 1 darkens. Blur and sharpen kernels both sum to 1: sharpening changes local contrast, not overall brightness. Edge-detection kernels deliberately sum to 0 so flat areas go black. When weights are computed at runtime, as in a Gaussian loop, divide by their total to bring the sum back to 1.
- How does bilateral filtering preserve edges while smoothing?
Each neighbor gets two weights that are multiplied together: one from spatial distance (as in a normal blur) and one from color similarity. A neighbor only contributes much if it is both close and similar in color. Inside a uniform region both weights are high and the pixels average out; across an edge the color weight is close to zero, so the two sides don't blend.
- Why might you need multiple passes for certain effects?
Some effects need the complete result of one step as the input of the next. Bloom extracts bright areas, blurs them, then combines them with the original. In SwiftUI you can chain layerEffect modifiers for the steps that each take one input, but a single shader only receives one layer. The final combine has to happen outside the shader (for example with .blendMode(.plusLighter)) or in your own Metal render passes.
Further Exploration
- Fourier domain filtering: converting an image to frequencies, editing them, and converting back
- Anisotropic filtering: smoothing that follows the direction of edges instead of spreading equally
- Temporal filtering: blending with previous frames to reduce noise over time
- Machine learning filters: effects produced by neural networks
- HDR processing: tone mapping and combining several exposures
Next Chapter Preview: This is the last chapter. You can now read and combine pixels with layerEffect, chain effects, and pick a maxSampleOffset that matches what your shader reads. The appendices cover what comes after building an effect: shipping shaders in a production app (Appendix A), organising your shader library (Appendix B), accessibility such as reduced motion (Appendix C), and a performance reference (Appendix D).