From hard edges to smooth ones
Put two circles side by side, one drawn with step() and one with a soft edge, and almost anyone will tell you the second looks better, even if they couldn't say why. The first has a jagged, stair-stepped outline. The second looks like something a designer drew.
You've already used smoothstep() in earlier chapters to soften an edge. In this chapter I want to open it up and look at two jobs it does:
- Anti-aliasing. Making a shape's edge exactly as soft as it needs to be (about one pixel) so it looks clean at any size and on any screen. The tool for sizing that edge is
fwidth(). - Transitions. Easing a value from one state to another so a mask, a reveal or a morph starts and stops gently instead of snapping.
By the end you'll also wire a shader into a real SwiftUI transition, so a view can appear with a circular reveal when you toggle it.
Three interpolation curves
All three curves below take an input t between 0 and 1 and return a value between 0 and 1. They differ in how fast the output changes along the way.
Linear interpolation
// Linear interpolation - mathematically correct, visually wrong
float linearFade(float x) {
return x; // 0 to 1 linearly
}
The output moves at the same speed the whole time. As a motion, that means it starts at full speed and stops dead, which reads as abrupt at both ends. As an edge, it means the gradient has a visible crease where the ramp begins and ends.
Smoothstep
Metal has smoothstep(edge0, edge1, x) built in. Here is what it computes, written out so you can see the steps (I've named it smoothstepPoly so it doesn't clash with the built-in if you paste it into a .metal file):
// The smoothstep polynomial (what Metal's built-in smoothstep computes)
float smoothstepPoly(float edge0, float edge1, float x) {
// Scale and bias x to 0..1 range
float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
// 3t² - 2t³: chosen so the slope is zero at t = 0 and t = 1
return t * t * (3.0 - 2.0 * t);
}
There are two steps. First, x is remapped so that edge0 becomes 0 and edge1 becomes 1, and anything outside that range is clamped. For smoothstep(0.4, 0.6, x) with x = 0.45, that gives t = (0.45 - 0.4) / 0.2 = 0.25. Second, t goes through the polynomial 3t² - 2t³.
Here is what the polynomial does to a few values, next to linear:
t: 0 0.25 0.5 0.75 1
linear: 0 0.25 0.5 0.75 1
smoothstep: 0 0.156 0.5 0.844 1
Smoothstep lags behind linear at the start, catches up exactly at the middle, and gets ahead near the end. The slope tells you why:
f(t) = 3t² - 2t³
f'(t) = 6t - 6t² f'(0) = 0, f'(0.5) = 1.5, f'(1) = 0
f''(t) = 6 - 12t f''(0) = 6, f''(1) = -6
The first derivative (the speed) is zero at both ends, so the value eases out of 0 and settles into 1. In the middle it moves 1.5 times faster than linear to make up the time. It's the lowest-degree polynomial that goes from 0 to 1 with zero slope at both ends, which is why it's the standard choice.
The second derivative (the acceleration) is not zero at the ends. Outside the 0 to 1 range the curve is flat, so its acceleration is 0; right inside, it's 6. That jump is invisible on an edge, but in motion it can show up as a slight kick as something starts moving.
Smootherstep
// Even smoother with zero second derivative at edges
float smootherstep(float edge0, float edge1, float x) {
float t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);
// 6t^5 - 15t^4 + 10t^3
return t * t * t * (t * (t * 6.0 - 15.0) + 10.0);
}
Smootherstep (Ken Perlin's variant) uses a fifth-degree polynomial. Its first derivative is 30t²(1 - t)² and its second is 60t(1 - t)(1 - 2t), and both are zero at t = 0 and t = 1, so speed and acceleration both start and end at rest. The price is a steeper middle (slope 1.875 at t = 0.5) and a few extra multiplications. At t = 0.25 it returns about 0.104, compared with 0.156 for smoothstep.
Metal does not have a built-in smootherstep. If you use it, define this helper in the same .metal file, above the shader that calls it.
Comparing the curves
The shader below plots all three. For each pixel it computes the curve's value at uv.x and lights the pixel if uv.y is within 0.01 of it. Remember that SwiftUI's y axis points down, so the curves start at the top-left and end at the bottom-right: they look upside down compared with a maths textbook.
Transition Curves Comparison
Visual comparison of linear (red), smoothstep (green), and smootherstep (blue) interpolation curves
[[ stitchable ]] half4 transitionCurves(
float2 position,
half4 color,
float2 size
) {
float2 uv = position / size;
// Three different transition curves
float linear = uv.x;
float smooth = smoothstep(0.0, 1.0, uv.x);
float smoother = smootherstep(0.0, 1.0, uv.x);
// Plot each curve
float plot_linear = step(abs(uv.y - linear), 0.01);
float plot_smooth = step(abs(uv.y - smooth), 0.01);
float plot_smoother = step(abs(uv.y - smoother), 0.01);
// Color code: red=linear, green=smoothstep, blue=smootherstep
return half4(
plot_linear,
plot_smooth,
plot_smoother,
1.0
);
}step(abs(uv.y - linear), 0.01) returns 1 when 0.01 >= abs(uv.y - linear), so each line is a hard-edged band 0.02 tall. Look closely at the lines in the preview and you'll see they're jagged, which is the problem the next section solves.
Anti-aliasing: why hard edges look jagged
What a pixel sees at an edge
Your shader runs once per pixel and decides that pixel's color from a single point, the pixel's center. A circle's mathematical edge, though, passes through pixels at arbitrary places. Near the edge, some pixels are 90% inside the circle, some 50%, some 10%.
step() ignores that. It looks at the center of each pixel and answers "inside" or "outside", so every edge pixel becomes fully on or fully off:
Mathematical edge step(): all or nothing What you want: coverage
cutting across pixels
┌───┬───┬───┐ ┌───┬───┬───┐ ┌───┬───┬───┐
│ ░░│ │ │ │███│ │ │ │▓▓▓│░░░│ │
├──╲┼───┼───┤ ├───┼───┼───┤ ├───┼───┼───┤
│███╲░░░│ │ │███│███│ │ │███│▓▓▓│░░░│
├───┼─╲─┼───┤ ├───┼───┼───┤ ├───┼───┼───┤
│███│███╲░░░│ │███│███│███│ │███│███│▓▓▓│
└───┴───┴───┘ └───┴───┴───┘ └───┴───┴───┘
Along a curve or a diagonal, the point where pixels flip from on to off jumps in whole-pixel steps, and that staircase is what we call aliasing (or "jaggies"). When the shape moves, edge pixels pop between on and off from one frame to the next, so the outline shimmers or crawls.
The value that looks right is the fraction of the pixel the shape covers. Computing that exactly is expensive, but there's a cheap approximation: measure how far the pixel center is from the edge, and fade from 1 to 0 across a band about one pixel wide. That's what smoothstep does here. Using distance in pixels, with the band running from half a pixel inside to half a pixel outside (1.0 - smoothstep(-0.5, 0.5, d)):
distance from edge (pixels): -1 -0.5 -0.25 0 0.25 0.5 1
step: 1 1 1 0/1 0 0 0
smoothstep band: 1 1 0.84 0.5 0.16 0 0
A pixel whose center sits exactly on the edge gets 0.5, half covered, and its neighbors get partial values that taper off. That's anti-aliasing.
The catch is the band width. "One pixel" in your shader's units depends on the view size and the screen's scale, and you don't know either ahead of time. fwidth() measures it for you.
Sizing the edge band with fwidth()
Anti-Aliased Circle
Smooth circle edges using fwidth() for resolution-independent anti-aliasing - compare the silky edges to pixelated shapes
[[ stitchable ]] half4 antiAliasedCircle(
float2 position,
half4 color,
float2 size,
float edgeSoftness // 0 to 0.5; 0.5 gives a one-pixel band
) {
float2 uv = position / size;
float2 center = uv - 0.5;
float radius = 0.3;
float dist = length(center);
// fwidth() returns how much dist changes from this pixel to its
// neighbors: the size of one pixel, measured in dist's units (uv here)
float pixelWidth = fwidth(dist);
// The band spans radius ± pixelWidth * edgeSoftness,
// so it is 2 * edgeSoftness pixels wide
float circle = 1.0 - smoothstep(
radius - pixelWidth * edgeSoftness,
radius + pixelWidth * edgeSoftness,
dist
);
return half4(circle, circle, circle, 1.0);
}In this example dist is measured in uv units, where 1.0 is the full width of the view. fwidth(dist) tells you how much dist changes between this pixel and the next, which is one pixel expressed in uv units. Multiply it by edgeSoftness and you get a band whose width is counted in pixels: at 0.5 the band is one pixel wide, at 1.0 two pixels, and near 0 it collapses back into a hard step() edge. In the Xcode project the slider runs from 0 to 0.5, so dragging it from left to right shows the jaggies disappearing.
Many shaders use smoothstep(r - w, r + w, d) with w = fwidth(d), which is a two-pixel band. It's a little softer than true coverage and a common default because it hides aliasing well on moving shapes.
How fwidth() works
// fwidth() is approximately:
// abs(dfdx(value)) + abs(dfdy(value))
//
// It tells you: "How much does this value change between adjacent pixels?"
// That's what lets the edge band stay one pixel wide at any size
The GPU doesn't run your shader on one pixel at a time. It runs it on small 2×2 blocks of neighboring pixels in lockstep. Because the four pixels in a block compute the same expression at the same time, the GPU can subtract one pixel's value from its neighbor's:
dfdx(v)is the difference invbetween the pixel and its horizontal neighbor.dfdy(v)is the same thing vertically.fwidth(v)adds their absolute values.
These are Metal's names; GLSL calls the first two dFdx and dFdy, which won't compile in Metal.
Take a 300×300 point view on a 3x iPhone. Moving one pixel to the right moves uv.x by 1 / 900 ≈ 0.0011. Near the circle's right-hand edge, dist changes by about that much per pixel horizontally and hardly at all vertically, so fwidth(dist) ≈ 0.0011. On a 2x iPad, or in a 600-point view, the number changes, and the band adjusts with it. You never hard-code it.
Because fwidth adds the horizontal and vertical changes instead of taking the length of the gradient, it overestimates on diagonals (by up to about 1.41 at 45°). Edges at an angle get a slightly wider band. In practice nobody notices.
The smoothing width in points and pixels
SwiftUI gives your shader position in points, but it rasterises the view at the screen's scale, and the shader runs once per device pixel. On a 3x screen, neighboring pixels have positions one third of a point apart, so fwidth(position.x) is about 0.33 there and 0.5 on a 2x screen.
That gives you two ways to think about an edge width:
- A width from
fwidth()is one device pixel, which is1 / displayScalepoints (0.33 pt at 3x, 0.5 pt at 2x). The edge looks equally crisp everywhere. - A hard-coded width is a fraction of the view. A band of 0.02 in uv units on a 300-point view is 6 points, which is 18 pixels at 3x: clearly soft. On a 50-point view the same 0.02 is 1 point. The softness changes with the size of the view.
Use fwidth() when you want a clean edge. Use a hard-coded width when the softness is a design choice, like a blurred mask, and should scale with the view.
Masks, reveals and gradients
The same smoothstep edge that anti-aliases a circle also makes masks and reveals. The only difference is the band width: a pixel or two for a crisp edge, a big chunk of the view for a soft fade.
A soft-edged mask
Smooth Mask
Rotating diagonal mask with smooth edges - demonstrates how smoothstep creates professional masking effects
[[ stitchable ]] half4 smoothMask(
float2 position,
half4 color,
float2 size,
float maskPosition, // 0-1, where the mask is
float maskSoftness, // 0-0.5, how soft the edge is
float maskAngle // rotation angle in radians
) {
float2 uv = position / size;
// Rotate UV coordinates around center
float2 centered = uv - 0.5;
float cosAngle = cos(maskAngle);
float sinAngle = sin(maskAngle);
float2 rotated = float2(
centered.x * cosAngle - centered.y * sinAngle,
centered.x * sinAngle + centered.y * cosAngle
);
// Create smooth diagonal mask
float mask = smoothstep(
maskPosition - maskSoftness,
maskPosition + maskSoftness,
rotated.x + 0.5 // Back to 0-1 range
);
// Apply mask to original color
return half4(color.rgb * mask, color.a * mask);
}The shader moves the origin to the center of the view, rotates the coordinates by maskAngle, and then uses the rotated x coordinate as the input to smoothstep. With maskPosition = 0.5 and maskSoftness = 0.1, pixels whose rotated x is below 0.4 are hidden, pixels above 0.6 are fully visible, and the 0.2-wide strip between them fades. Rotating the coordinates instead of the mask is the usual trick: the mask is always a simple vertical edge in its own coordinate system.
Look at the return line: it multiplies both the color and the alpha by mask. SwiftUI colors are premultiplied (Chapter 1 covers this), so fading a pixel to transparent means scaling all four channels. If you only scaled alpha, the RGB values would end up larger than alpha and the hidden part of the view would glow instead of disappearing.
Circular reveal with a glowing edge
Circular Reveal
Animated circular reveal effect with glowing edges - perfect for transitions and UI reveals
[[ stitchable ]] half4 circularReveal(
float2 position,
half4 color,
float2 size,
float2 revealCenter, // UV coordinates of reveal center
float revealProgress, // 0-1, animation progress
float edgeGlow // 0-1, intensity of edge glow
) {
float2 uv = position / size;
// Distance from reveal center
float dist = distance(uv, revealCenter);
// Radius grows linearly with progress; easing comes from whatever animates progress
float maxRadius = length(float2(1.0, 1.0)); // Corner to corner
float currentRadius = revealProgress * maxRadius;
// Create smooth reveal with glowing edge
float edgeWidth = 0.1;
float reveal = smoothstep(
currentRadius + edgeWidth,
currentRadius,
dist
);
// Add glow in a ring just inside the edge
float glowMask = smoothstep(
currentRadius - edgeWidth * 2.0,
currentRadius - edgeWidth,
dist
) * (1.0 - smoothstep(
currentRadius,
currentRadius + edgeWidth,
dist
));
// Combine reveal and glow
half3 finalColor = color.rgb * reveal;
finalColor += half3(edgeGlow, edgeGlow * 0.7, edgeGlow * 0.3) * glowMask;
return half4(finalColor, color.a * reveal);
}Trace one pixel. Say revealProgress = 0.25, so currentRadius = 0.25 × 1.414 ≈ 0.35, and the pixel is 0.4 away from the center. The reveal band runs from 0.35 (fully visible) to 0.45 (hidden), and 0.4 is halfway, so reveal = 0.5: the pixel is half faded.
Two details in this shader are worth knowing:
- The edges in
smoothstep(currentRadius + edgeWidth, currentRadius, dist)are written in reverse order to get a fade from 1 down to 0. It works on Apple GPUs, but the Metal specification says the result is undefined whenedge0is not less thanedge1. The safe way to write the same thing is1.0 - smoothstep(currentRadius, currentRadius + edgeWidth, dist). See pitfall 5 below. maxRadiusis the length of the view's diagonal (√2 ≈ 1.414 in uv units), which is far enough to cover the view from any center, even a corner. With the reveal centered at(0.5, 0.5), the farthest corner is only about 0.707 away, so the view is fully revealed by roughlyprogress = 0.57and the rest of the animation changes nothing visible. For a centered reveal, dividemaxRadiusby 2, as the Xcode project's version does.
The glow is the product of two smoothsteps. The first rises from 0 to 1 between currentRadius - 0.2 and currentRadius - 0.1; the second falls from 1 to 0 between currentRadius and currentRadius + 0.1. Multiplying them leaves a ring that is bright only where both are high, around the edge of the reveal. The glow color is added to RGB even where alpha is falling, so in that band RGB ends up larger than alpha. In premultiplied terms that means "add light on top of what's behind", which is the glowing look we want here. It's the same effect that's a bug in the mask above and a feature here.
In the Xcode project, you can drag your finger over the image to move revealCenter. The drag location in points is divided by the view's size (300) to turn it into uv coordinates.
Directional gradient
Smooth Gradient
Professional rotating gradient with adjustable smoothness - shows how to create silky smooth color transitions
[[ stitchable ]] half4 smoothGradient(
float2 position,
half4 color,
float2 size,
float3 color1, // Start color
float3 color2, // End color
float angle, // Gradient angle
float smoothness // 0-1, width of the soft ramps at each end
) {
float2 uv = position / size;
// Create directional gradient
float2 dir = float2(cos(angle), sin(angle));
float grad = dot(uv - 0.5, dir) + 0.5;
// Shape the gradient: ramp up over the first 'smoothness' of the range,
// stay at 1 in the middle, ramp back down over the last 'smoothness'.
// Result: a band of color2 with soft edges and color1 at both ends.
if (smoothness > 0.0) {
grad = smoothstep(0.0, smoothness, grad) *
smoothstep(1.0, 1.0 - smoothness, grad);
}
// Interpolate colors (mix works on float3; convert to half3 explicitly)
half3 result = half3(mix(color1, color2, grad));
return half4(result, 1.0);
}dot(uv - 0.5, dir) projects each pixel onto the direction of the gradient: it tells you how far along dir the pixel sits, measured from the center. Adding 0.5 puts the result roughly in the 0 to 1 range. With angle = 0, dir = (1, 0) and grad is just uv.x.
The smoothness step is not a "make it smoother" control, despite the name. It reshapes grad into a plateau: with smoothness = 0.2, grad ramps from 0 to 1 over the first 20% of the view, stays at 1, then ramps back to 0 over the last 20%. So you get color2 in the middle fading to color1 at both ends. If what you want is a plain two-color gradient with eased ends, replace the whole if block with one line, grad = smoothstep(0.0, 1.0, grad);.
Using a shader as a SwiftUI transition
A SwiftUI transition describes how a view looks while it's being inserted or removed. You can build one from any view modifier: give SwiftUI the modifier in its "not present" state and in its "fully present" state, and it animates between them. If that modifier applies a shader, the shader becomes the transition.
struct SmoothRevealModifier: ViewModifier, Animatable {
var progress: Double
// SwiftUI interpolates this value frame by frame during the animation
var animatableData: Double {
get { progress }
set { progress = newValue }
}
func body(content: Content) -> some View {
content
.visualEffect { content, proxy in
content.colorEffect(
ShaderLibrary.circularReveal(
.float2(proxy.size),
.float2(0.5, 0.5), // Center reveal
.float(Float(progress)),
.float(0.8) // Edge glow
)
)
}
}
}
extension AnyTransition {
static var smoothReveal: AnyTransition {
.modifier(
active: SmoothRevealModifier(progress: 0),
identity: SmoothRevealModifier(progress: 1)
)
}
}
.modifier(active:identity:) takes two versions of the modifier. active is how the view looks when it isn't in the hierarchy (progress 0, fully hidden) and identity is how it looks normally (progress 1, fully revealed). When the view is inserted inside an animation, SwiftUI animates from active to identity; when it's removed, from identity back to active.
The Animatable conformance is what makes it move. SwiftUI only interpolates properties it knows about, and for a view modifier that means animatableData. Without it, SwiftUI has no way to produce the in-between values 0.1, 0.2, 0.3..., so progress jumps straight from 0 to 1 and the view pops in. The same rule applies to any shader argument: changing a @State value inside withAnimation does not animate a .float() argument unless an Animatable view or modifier sits in between.
.visualEffect is what gives the shader its size. The closure receives a GeometryProxy for the view, and proxy.size is passed in as the size argument. colorEffect doesn't give the shader the view's size on its own.
Using it looks like any other transition:
if showBox {
RoundedRectangle(cornerRadius: 20)
.fill(.blue)
.frame(width: 200, height: 200)
.transition(.smoothReveal)
}
Button("Tap to transition") {
withAnimation(.easeInOut(duration: 1.0)) {
showBox.toggle()
}
}
The animation curve you pass to withAnimation decides how progress moves over time, so the easing lives on the SwiftUI side and the shader only maps progress to pixels. On iOS 17 and later you can also write a type that conforms to the Transition protocol and apply the modifier with progress 1 or 0 depending on phase.isIdentity. The modifier still needs to be Animatable for the shader to animate.
Edge detection with derivatives
dfdx and dfdy aren't only for sizing edges. Applied to the color of an image, they tell you how fast the color changes between neighboring pixels, and a sudden change is an edge.
Smooth Edge Detection
[[ stitchable ]] half4 edgeDetection(
float2 position,
half4 color,
float2 size,
float threshold, // Edge detection sensitivity
float smoothing // Edge smoothness
) {
float2 uv = position / size;
// Get color luminance (ITU-R BT.601 weights: how bright each channel looks to the eye)
float center = dot(color.rgb, half3(0.299, 0.587, 0.114));
// How much luminance changes to the neighboring pixel
float2 grad = float2(
dfdx(center), // Horizontal change
dfdy(center) // Vertical change
);
float edge = length(grad);
// Smooth threshold
float edgeMask = smoothstep(threshold - smoothing, threshold + smoothing, edge);
// Stylized output: white background, black edges
float output = 1.0 - edgeMask;
return half4(output, output, output, 1.0);
}The shader converts the pixel's color to a single brightness value, then asks the GPU how much that brightness differs from the neighboring pixel horizontally (dfdx) and vertically (dfdy). length(grad) combines the two into one "how much is changing here" number. In a flat area of the photo it's close to 0; across the outline of an object it's large.
Then smoothstep is used as a soft threshold instead of a hard cut. With threshold = 0.1 and smoothing = 0.05, changes below 0.05 count as "no edge", changes above 0.15 count as "edge", and the values in between fade, which keeps the lines from breaking up into noise.
This is a deliberately simple method. A colorEffect shader only knows its own pixel's color, and derivatives only compare it with the one neighbor in its 2×2 block, so the lines are thin and can look patchy. Proper edge detectors such as Sobel read eight neighbors, which needs layerEffect and layer.sample(), covered in Chapter 10.
Common pitfalls
Pitfall 1: A hard-coded edge width
// WRONG for anti-aliasing - the band is 0.02 of the view, whatever its size:
// 6 pt (18 px at 3x) on a 300 pt view, 1 pt on a 50 pt view
float circle = 1.0 - smoothstep(0.49, 0.51, dist);
// CORRECT - the band is about one pixel at any view size or display scale
float pixelWidth = fwidth(dist);
float circle = 1.0 - smoothstep(
0.5 - pixelWidth,
0.5 + pixelWidth,
dist
);
The first version can look fine on the device you test with and blurry or jagged on another. If the goal is a clean edge, size it with fwidth().
Pitfall 2: Over-smoothing
// WRONG - Too much smoothing creates blurry mess
float edge = smoothstep(0.0, 1.0, dist); // Entire range!
// CORRECT - Controlled smoothing
float edge = smoothstep(0.48, 0.52, dist); // Just enough
When the band covers the whole 0 to 1 range there's no edge left, only a gradient. A deliberate soft edge should be a narrow band around the value where the edge sits. As pitfall 1 shows, a fixed band like 0.48 to 0.52 is a design choice that scales with the view, not anti-aliasing.
Pitfall 3: Mixing colors in gamma space
// WRONG - Linear blending in sRGB space
half3 blended = mix(color1, color2, 0.5);
// CORRECT - Gamma-correct blending (2.2 approximates the sRGB curve)
half3 linear1 = pow(color1, 2.2);
half3 linear2 = pow(color2, 2.2);
half3 blended = pow(mix(linear1, linear2, 0.5), 1.0/2.2);
The sRGB values you copy from a design tool are gamma-encoded: 0.5 isn't half as much light as 1.0, it's about 22%. Mixing encoded values gives midpoints that look darker and muddier than they should, which shows most on gradients between saturated colors like red and green. Converting to linear light, mixing, and converting back gives an even-looking blend. Whether it's worth the two pow calls depends on the colors; for subtle gradients you often can't tell.
Pitfall 4: Fading alpha without fading the color
// WRONG - RGB stays at full strength while alpha drops
return half4(color.rgb, color.a * mask);
// CORRECT - premultiplied: scale every channel
return half4(color.rgb * mask, color.a * mask);
SwiftUI passes and expects premultiplied colors. When you fade a view out with a mask, multiply RGB by the same factor as alpha. The wrong version leaves RGB larger than alpha, and the "hidden" part of the view shows up as a bright, additive haze instead of disappearing.
Pitfall 5: Reversed smoothstep edges
// Undefined in the Metal spec: edge0 must be less than edge1
float fadeOut = smoothstep(0.5, 0.4, dist);
// Defined: keep the edges in order and flip the result
float fadeOut = 1.0 - smoothstep(0.4, 0.5, dist);
You'll see the reversed form in a lot of shader code, including some in this chapter, and on Apple GPUs it currently gives the mirrored curve you'd expect. The Metal specification still says the result is undefined when edge0 >= edge1, so the 1.0 - smoothstep(...) form is the one to write in new code.
Distance fields and morphing
Chapter 8 is about distance fields in depth. Here's a preview of why they matter for smooth edges: if you have a function that returns the distance to a shape's edge, you can anti-alias any shape the same way you did the circle.
Distance field shapes
Distance Field Shapes
Smooth animated shapes (circle → square → star) with perfect borders using signed distance fields
[[ stitchable ]] half4 distanceFieldShape(
float2 position,
half4 color,
float2 size,
float shapeType, // 0=circle, 1=square, 2=star
float borderWidth, // Width of border
float3 fillColor,
float3 borderColor
) {
float2 uv = position / size;
float2 centered = uv - 0.5;
float dist = 0.0;
// Calculate distance based on shape
if (shapeType < 0.5) {
// Circle
dist = length(centered) - 0.3;
} else if (shapeType < 1.5) {
// Square
float2 d = abs(centered) - 0.3;
dist = length(max(d, 0.0)) + min(max(d.x, d.y), 0.0);
} else {
// Star (simplified 5-point)
float angle = atan2(centered.y, centered.x);
float r = length(centered);
float star = 0.3 + 0.1 * cos(5.0 * angle);
dist = r - star;
}
// Create smooth shape with border
float shape = 1.0 - smoothstep(-borderWidth, 0.0, dist);
float border = smoothstep(-borderWidth, -borderWidth * 0.5, dist);
// Combine colors: fill inside (border = 0), border color near the edge (border = 1)
half3 result = half3(mix(fillColor, borderColor, border) * shape);
return half4(result, shape);
}Each branch computes a signed distance: negative inside the shape, zero on the edge, positive outside. The circle's is the distance from the center minus the radius. The square and star formulas are explained in Chapter 8; the star one isn't a true distance, just "how far past the wavy radius am I", but it's close enough for smoothstep to draw a clean edge.
Once you have dist, the shape and its border are two smoothsteps on the same number. shape fades from 1 to 0 across the last borderWidth before the edge. border goes from 0 to 1 between -borderWidth and -borderWidth * 0.5, so it's 0 in the interior and 1 in the outer band, and mix(fillColor, borderColor, border) uses it to pick the color. Because dist means the same thing for every shape, the coloring code doesn't care which shape it's drawing.
Morphing between shapes
Shape Morph
Smooth animated morph between circle and square using distance field interpolation - shows seamless shape transitions
[[ stitchable ]] half4 shapeMorph(
float2 position,
half4 color,
float2 size,
float morphProgress // 0=circle, 1=square
) {
float2 uv = position / size;
float2 centered = (uv - 0.5) * 2.0; // -1 to 1 range
// Distance functions for both shapes
float circleDist = length(centered) - 0.6;
float squareDist = max(abs(centered.x), abs(centered.y)) - 0.6;
// Smooth interpolation between shapes
float dist = mix(circleDist, squareDist, smoothstep(0.0, 1.0, morphProgress));
// Anti-aliased edge
float shape = 1.0 - smoothstep(-0.01, 0.01, dist);
// Add inner gradient for depth
float innerGrad = 1.0 - smoothstep(-0.6, -0.1, dist);
half3 shapeColor = mix(
half3(0.2, 0.3, 0.8), // Edge color
half3(0.4, 0.6, 1.0), // Center color
innerGrad
);
return half4(shapeColor * shape, shape);
}To morph, the shader computes the distance to both shapes and blends the two distances with mix. At morphProgress = 0 you get the circle's distance, at 1 the square's, and in between a shape that's partly each. Blending the distances, rather than the two finished images, is what makes the outline itself change shape instead of one shape cross-fading over the other.
Two things to notice:
smoothstep(0.0, 1.0, morphProgress)eases the morph inside the shader. If you also animatemorphProgresswith.easeInOutin SwiftUI, the motion gets eased twice: an even slower start and a faster middle. Pick one place to do the easing.- The anti-aliased edge uses a fixed band of ±0.01 in a space that runs from -1 to 1, which is 0.005 of the view on each side. That's pitfall 1 again. As an exercise, replace it with
fwidth(dist)and compare the edges at different view sizes.
Challenges
Challenge 1: Smooth Wave Transition

Create a waveTransition shader that reveals content behind a wavy, soft edge. As progress goes from 0 to 1, the edge should sweep across the view, and the wave in the edge should keep moving over time.
Metal Shader Hint:
Use sin() for wave shape
Use smoothstep() for smooth edges
Animate with time parameter
One way to build it: offset the x position of the edge by sin(uv.y * frequency + time) * amplitude, then use smoothstep on uv.x around that edge. Multiply both RGB and alpha by the mask so the view fades to transparent correctly. The Xcode solution's signature is waveTransition(float2 position, half4 color, float2 size, float time, float progress).
SwiftUI Template:
struct WaveTransitionView: View {
@State private var progress: Float = 0.0
private let startDate = Date()
var body: some View {
VStack {
TimelineView(.animation) { timeline in
// Elapsed seconds since the view appeared, small enough to stay precise as a Float
let time = Float(timeline.date.timeIntervalSince(startDate))
Image("sample_image")
.resizable()
.aspectRatio(contentMode: .fit)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.waveTransition(
.float2(proxy.size),
.float(time),
.float(progress)
))
}
.frame(height: 300)
}
HStack {
Text("Progress")
Slider(value: $progress, in: 0...1)
}
.padding()
}
}
}
TimelineView(.animation) redraws every frame and hands you the current date, which is the standard way to drive time in a shader. The slider controls progress directly. If you want a button that animates progress, a plain withAnimation won't do it, for the reason explained in the transition section; wrap the shader in an Animatable modifier like SmoothRevealModifier.
Challenge 2: Glow Effect

Create a glowingEdge shader that draws a shape and adds a smooth glow around it that pulses over time.
Metal Shader Hint:
Detect edges using distance
Create multiple smoothstep layers for glow
Combine with original shape
Start with the anti-aliased circle from this chapter. For the glow, measure how far each pixel is outside the circle (max(0.0, dist - radius)) and turn that into a brightness that falls off with distance. Layered smoothsteps work, and so does an exponential falloff, exp(-glowDist / glowRadius), which is what the Xcode solution uses. Multiply the glow by something like sin(time * 3.0) * 0.3 + 0.7 to make it pulse.
SwiftUI Template:
struct GlowingEdgeView: View {
@State private var glowIntensity: Float = 1.0
@State private var glowRadius: Float = 0.1
@State private var pulseAnimation: Float = 0.0
let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Rectangle()
.fill(Color.black)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.glowingEdge(
.float2(proxy.size),
.float(glowIntensity),
.float(glowRadius),
.float(pulseAnimation)
))
}
.frame(height: 300)
VStack {
HStack {
Text("Intensity")
Slider(value: $glowIntensity, in: 0...2)
}
HStack {
Text("Radius")
Slider(value: $glowRadius, in: 0.05...0.3)
}
}
.padding()
}
.onReceive(timer) { _ in
pulseAnimation += 1/60.0
}
}
}
Challenge 3: Smooth Kaleidoscope

Create a kaleidoscope shader that splits the view into pie-slice segments around the center, with smooth transitions at the segment boundaries.
Metal Shader Hint:
Use polar coordinates
Apply modulo to angle for repetition
Smooth transitions at segment boundaries
Convert the centered uv to an angle with atan2, divide the circle into segments slices, and work out each pixel's angle within its slice. Its distance to the nearest slice boundary, min(angleInSegment, segmentAngle - angleInSegment), goes into smoothstep to darken the seams softly.
A real kaleidoscope copies pixels from one slice into the others, which means reading colors at other positions. A colorEffect shader can't do that; it only sees its own pixel. With colorEffect you can tint each slice and shade the seams. The Xcode project includes a second version, kaleidoscopeLayer, that uses layerEffect and layer.sample() to do the mirroring for real; Chapter 10 explains how sampling works.
SwiftUI Template:
struct KaleidoscopeView: View {
@State private var segments: Float = 6.0
@State private var rotation: Float = 0.0
@State private var smoothness: Float = 0.1
var body: some View {
VStack {
Image("colorful_image")
.resizable()
.aspectRatio(contentMode: .fit)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.kaleidoscope(
.float2(proxy.size),
.float(segments),
.float(rotation),
.float(smoothness)
))
}
.frame(height: 300)
VStack {
HStack {
Text("Segments: \(Int(segments))")
Slider(value: $segments, in: 3...12, step: 1)
}
HStack {
Text("Rotation")
Slider(value: $rotation, in: 0...6.28)
}
HStack {
Text("Smoothness")
Slider(value: $smoothness, in: 0...0.3)
}
}
.padding()
}
}
}
Challenge 4: Smooth Radar Sweep

Create a radarSweep shader that simulates a radar display with a rotating sweep line that leaves a fading trail. Detected objects should appear as blips that pulse smoothly when hit by the sweep.
Metal Shader Requirements:
- Create a rotating sweep line with perfect anti-aliasing
- Add a fading trail that follows the sweep
- Generate random "blips" that represent detected objects
- Make blips pulse smoothly when the sweep passes over them
- Include range rings with smooth edges
This challenge puts the chapter's pieces together in polar coordinates. The sweep line is an edge in angle instead of distance, so you anti-alias it with fwidth() of the angle difference. The trail is a wide smoothstep behind the line, the range rings are thin anti-aliased circles, and the blip positions come from the hash functions in Chapter 6. Normalize the angle to 0 to 1 and use fract() to wrap the difference between a pixel's angle and the sweep angle into the range -0.5 to 0.5; otherwise the trail breaks where the angle wraps from 1 back to 0.
SwiftUI Template:
struct RadarSweepView: View {
@State private var timeValue: Float = 0.0
@State private var sweepSpeed: Float = 1.0
@State private var trailLength: Float = 0.3
@State private var blipCount: Float = 8.0
@State private var showRangeRings: Bool = true
let timer = Timer.publish(every: 1/60.0, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("Radar Sweep")
.font(.title2)
.padding()
Rectangle()
.fill(Color.black)
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.radarSweep(
.float2(proxy.size),
.float(timeValue),
.float(sweepSpeed),
.float(trailLength),
.float(blipCount),
.float(showRangeRings ? 1.0 : 0.0)
))
}
.frame(width: 350, height: 350)
.clipShape(Circle())
.overlay(Circle().stroke(Color.green.opacity(0.5), lineWidth: 2))
VStack(spacing: 15) {
HStack {
Text("Sweep Speed")
Slider(value: $sweepSpeed, in: 0.5...3.0)
}
HStack {
Text("Trail Length")
Slider(value: $trailLength, in: 0.1...0.5)
}
HStack {
Text("Objects: \(Int(blipCount))")
Slider(value: $blipCount, in: 0...20, step: 1)
}
Toggle("Range Rings", isOn: $showRangeRings)
}
.padding()
}
.onReceive(timer) { _ in
timeValue += 1/60.0
}
}
}
In the Xcode solution, sweepSpeed is in revolutions per second (fract(time * sweepSpeed) is the sweep angle as a fraction of a full turn), so 1.0 is one turn per second.
What smooth effects cost
// Expensive: a box blur inside a layerEffect reads 121 pixels
// (an 11 x 11 grid) for every output pixel
half4 sum = half4(0.0);
for (int i = -5; i <= 5; i++) {
for (int j = -5; j <= 5; j++) {
sum += layer.sample(position + float2(i, j));
}
}
half4 blurred = sum / 121.0;
// Cheap: smoothstep is a clamp and a few multiply-adds, no memory reads
float edge = smoothstep(0.4, 0.6, value);
// Compute shared values once and reuse them
float dist = length(uv - center);
float aa = fwidth(dist);
float core = 1.0 - smoothstep(0.3 - aa, 0.3 + aa, dist); // crisp disc
float halo = 1.0 - smoothstep(0.3, 0.6, dist); // soft glow around it
smoothstep, mix and fwidth are all cheap: a few arithmetic instructions each. You don't need to avoid them or merge several into one. Merging usually changes the curve anyway, so smoothstep(0.2, 0.7, x) is not a faster version of three smoothsteps multiplied together; it's a different shape.
What costs real time is reading memory. Every layer.sample() call is a texture read, and a loop of them multiplies that by the number of iterations for every pixel on screen. When a shader is slow, look for sample loops first. After that, compute values like dist and fwidth(dist) once and reuse them, instead of recomputing the same distance for every layer of an effect.
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 and Answers
1. Why does smoothstep(0.4, 0.6, x) create better edges than step(0.5, x)?
Answer: step makes every pixel either fully inside or fully outside, based on the single point at its center. Along a curved or diagonal edge that produces a staircase, and when the shape moves, edge pixels pop on and off. smoothstep gives pixels in the band between 0.4 and 0.6 in-between values, which approximates how much of each pixel the shape actually covers. For a clean edge rather than a deliberately soft one, the band should be about one pixel wide, which is what fwidth() is for.
2. What does fwidth() do and why is it crucial for resolution-independent rendering?
Answer: fwidth(v) returns abs(dfdx(v)) + abs(dfdy(v)): how much v changes between this pixel and its horizontal and vertical neighbors. The GPU gets this by comparing values across the 2×2 block of pixels it shades together. The result is the size of one pixel measured in the units of v. If you use it as the width of your smoothstep band, the edge is always about one device pixel wide (0.33 pt on a 3x screen, 0.5 pt on a 2x screen), whatever the view's size or the display's scale. A hard-coded width like 0.02 is a fixed fraction of the view instead, so it's blurry on large views and jagged on small ones.
3. How does the smoothstep polynomial t²(3-2t) achieve smooth acceleration?
Answer: Its derivative is 6t(1 - t), which is 0 at t = 0 and at t = 1. So the value leaves 0 with zero speed and arrives at 1 with zero speed, and to make up for the slow ends it moves 1.5 times faster than linear in the middle. It's the lowest-degree polynomial that goes from 0 to 1 with zero slope at both ends. Its second derivative, 6 - 12t, is 6 and -6 at the ends, so the acceleration does jump when the motion starts and stops. Smootherstep removes that jump.
Linear interpolation, by comparison, starts and stops at full speed, which reads as abrupt.
4. When should you use smoothstep vs smootherstep?
Answer: Use smoothstep by default. It's built into Metal and for anti-aliasing the difference can't be seen, because the band is only a pixel wide.
Reach for smootherstep when the curve shapes something people watch over time or across a wide area: motion where a small kick at the start would be noticeable, or a wide gradient where you can see where the ramp begins and ends. It has zero acceleration at both ends as well as zero speed. You have to define it yourself, and it costs a few extra multiplications.
5. How do you anti-alias a complex shape like a star?
Answer: Calculate the signed distance to the shape, then use smoothstep with a width based on fwidth():
float dist = distanceToStar(position);
float pixelWidth = fwidth(dist);
float antiAliased = 1.0 - smoothstep(-pixelWidth, pixelWidth, dist);
distanceToStar stands for any function that is negative inside, zero on the edge and positive outside. It doesn't have to be an exact distance: because fwidth measures how fast your particular function changes per pixel, it adapts the band to it. What matters is that the function changes smoothly across the edge.
6. What's the relationship between smoothstep and SwiftUI's animation curves?
Answer: SwiftUI's .easeInOut is a cubic Bézier timing curve. Like smoothstep, it starts and ends with zero slope, so the two look similar, but they aren't identical. If you want an exact match, smoothstep is the Bézier curve with control points (1/3, 0) and (2/3, 1), so .timingCurve(1.0/3.0, 0, 2.0/3.0, 1, duration: 1.0) animates a value along exactly the same curve.
The more common mistake is easing twice: animating progress with .easeInOut in SwiftUI and then running it through smoothstep in the shader. Decide whether the easing lives in SwiftUI or in the shader, and keep the other side linear.
Further Exploration
- Signed distance fields (SDF): a function per shape that returns the distance to its edge. Chapter 8 covers them, and they make anti-aliasing any shape as easy as the circle here.
- Analytical anti-aliasing: computing the exact fraction of a pixel a shape covers, instead of approximating it with a smoothstep band.
- Temporal anti-aliasing: blending each frame with reprojected previous frames, using motion vectors to line them up.
- Bézier curve rendering: drawing smooth curves directly in a shader.
Next Chapter Preview: You can now give any edge a clean, one-pixel transition and ease values between states. Chapter 8 is about distance fields: describing shapes as functions that return the distance to their edge. You'll build circles, boxes and stars that way, combine them with union, intersection and subtraction, and anti-alias all of them with the fwidth() technique from this chapter.