What position gives you, and why you rarely use it raw
In Chapter 1 every pixel returned the same color. To draw anything (a gradient, a circle, a grid) each pixel has to compute a color from where it is, and that is what the position parameter is for. Almost every effect in this course boils down to a function that takes a position and returns a color.
The catch is that position arrives in a unit that's awkward to work with. If you write "make the pixel white when position.x is less than 150", you've drawn half the view on a 300-point-wide canvas and a third of it on a 450-point one. This chapter shows the three small transformations that fix this (normalizing, centering and aspect-ratio correction) and then uses them to draw gradients, circles and grids.
Where position and size come from
Position: points, origin top-left
SwiftUI calls your shader once for every pixel of the view and hands it that pixel's location in position. Three details matter:
- It's measured in points, the same unit you use in
.frame(width:height:), in the view's own coordinate space. It isn't measured in device pixels. (0, 0)is the top-left corner of the view.- x grows to the right and y grows downward, as in the rest of SwiftUI.
So for a view with .frame(width: 300, height: 200), position runs from about (0, 0) at the top-left to about (300, 200) at the bottom-right. On a 3x display that view covers 900 × 600 physical pixels. The shader still runs once per physical pixel, so neighboring pixels get positions that differ by a fraction of a point.
(0,0) ───────────── x grows ──────────▶ (300,0)
│
│ (150,100) is the middle
y grows
│
▼
(0,200) (300,200)
Size: you pass it in yourself
colorEffect gives your shader position and the pixel's current color. It does not give it the size of the view. Every shader in this chapter has a third parameter, float2 size, and that value comes from you, as an argument you send from Swift:
Rectangle()
.frame(width: 300, height: 200)
.visualEffect { content, proxy in
content.colorEffect(
ShaderLibrary.horizontalGradient(.float2(proxy.size))
)
}
.visualEffect hands you a GeometryProxy for the view it's attached to, and proxy.size is that view's size in points: (300, 200) here, which is the same unit position uses. .float2(...) converts the CGSize into a float2.
How the arguments line up with the Metal function:
Metal: half4 horizontalGradient(float2 position, half4 color, float2 size)
▲ ▲ ▲
SwiftUI fills these two automatically ────────────┘ │
Your first argument, .float2(proxy.size), lands here ──────────┘
SwiftUI always supplies the first two parameters. The arguments you pass in ShaderLibrary.name(...) fill the remaining parameters in order. If you forget .float2(proxy.size), size won't hold the view's size and every division below produces garbage.
A GeometryReader around the view works too (Challenge 4 uses one), and so does .boundingRect, a shader argument that arrives in Metal as a float4(x, y, width, height) describing the view's bounds. This chapter sticks with .visualEffect and proxy.size because it measures exactly the view the shader is drawing.
Step 1: normalize to UV coordinates
The first line of most shaders you'll write is:
float2 uv = position / size;
Dividing a float2 by a float2 divides each component separately: uv.x = position.x / size.x and uv.y = position.y / size.y. The result, called UV coordinates, runs from 0 to 1 in both directions however big the view is. Read uv.x = 0.25 as "a quarter of the way across".
A worked example on a 300 × 200 view:
Pixel position position / size uv
top-left (0, 0) (0/300, 0/200) (0, 0)
middle (150, 100) (150/300, 100/200) (0.5, 0.5)
right edge, a quarter down (300, 50) (300/300, 50/200) (1, 0.25)
bottom-right (300, 200) (300/300, 200/200) (1, 1)
Now the same rule works on any view. "White when uv.x is less than 0.5" always paints the left half, whether the view is 300 points wide or 1,000.
The transformation in code
float2 uv = position / size;
// position: (400, 300) on an 800x600 view
// size: (800, 600)
// uv: (0.5, 0.5) - exactly center, always
UV coordinate properties
(0, 0)is the top-left corner.(1, 1)is the bottom-right corner.(0.5, 0.5)is the exact center.- Both components stay between 0.0 and 1.0 for any view size.
Step 2: move the origin to the center
Circles, rings, spotlights and rotations are all described relative to a center point. With UV the center is (0.5, 0.5), so you subtract 0.5 to make the center (0, 0):
float2 uv = position / size;
float2 centered = uv - 0.5; // Range: -0.5 to 0.5
// or
float2 centered = (uv - 0.5) * 2.0; // Range: -1.0 to 1.0
Continuing the 300 × 200 example:
Pixel uv uv - 0.5 (uv - 0.5) * 2
top-left (0, 0) (-0.5, -0.5) (-1, -1)
middle (0.5, 0.5) (0, 0) (0, 0)
right edge, a quarter down (1, 0.25) (0.5, -0.25) (1, -0.5)
Negative x is left of center and negative y is above it (y still grows downward). Which version you use is a matter of taste. The -0.5 to 0.5 version keeps "0.3" meaning "30% of the view", which is what the examples below rely on. The -1 to 1 version is common in shader code you'll find online.
Step 3: correct for the aspect ratio
UV has one side effect: it squashes both axes into the same 0 to 1 range even when the view isn't square. On a 300 × 200 view, one unit of uv.x is 300 points but one unit of uv.y is only 200 points.
See what that does to distances. Take two pixels, each 60 points from the center, one to the right and one below:
60 points right of center: uv.x offset = 60 / 300 = 0.2
60 points below center: uv.y offset = 60 / 200 = 0.3
Same physical distance, different UV distance. So if you draw a circle with length(uv - 0.5) less than 0.3, its edge sits 0.3 × 300 = 90 points out horizontally and only 0.3 × 200 = 60 points out vertically. You get an ellipse 180 points wide and 120 points tall.
The fix is to stretch x back by the aspect ratio, size.x / size.y:
aspect = 300 / 200 = 1.5
60 points right: 0.2 × 1.5 = 0.3
60 points below: 0.3 (y unchanged)
Both offsets now equal 0.3, so equal distances on screen give equal numbers in the shader, and a radius of 0.3 means 0.3 × the view's height (60 points) in every direction. You'll see this in code under "Common pitfalls" below. An equivalent one-liner you'll also find in shader code is (position - 0.5 * size) / size.y: center in points first, then divide everything by the height.
The examples in this chapter all run on square views, where the aspect ratio is 1 and this step changes nothing. As soon as your view isn't square, you need it.
Your first pattern: a horizontal gradient
Horizontal Gradient
A simple black-to-white gradient demonstrating how to use normalized coordinates
[[ stitchable ]] half4 horizontalGradient(float2 position, half4 color, float2 size) {
float2 uv = position / size;
return half4(uv.x, uv.x, uv.x, 1.0);
}The shader uses uv.x as the red, green and blue values. When all three channels are equal you get a gray, so:
- At the left edge,
uv.x = 0.0, which gives black. - In the middle,
uv.x = 0.5, which gives mid gray. - At the right edge,
uv.x = 1.0, which gives white.
Swap uv.x for uv.y and the gradient runs from top to bottom instead, black at the top because y starts at 0 there.
Drawing shapes with distance
Circle using distance
Circle Using Distance
Creates a hard-edged circle using distance calculation
[[ stitchable ]] half4 circle(float2 position, half4 color, float2 size) {
float2 uv = position / size;
float2 center = uv - 0.5; // Center at (0,0)
float dist = length(center); // Distance from center
if (dist < 0.3) {
return half4(1.0, 1.0, 1.0, 1.0); // White inside
} else {
return half4(0.0, 0.0, 0.0, 1.0); // Black outside
}
}length(v) returns the length of a vector, sqrt(v.x * v.x + v.y * v.y). Because center is this pixel's offset from the middle of the view, length(center) is the pixel's distance from the middle. A circle is just the set of points closer than some radius, so one comparison draws it.
Tracing two pixels on a 300 × 300 view:
Pixel at position (180, 150):
uv = (180/300, 150/300) = (0.6, 0.5)
center = (0.1, 0.0)
dist = sqrt(0.1² + 0.0²) = 0.1 → less than 0.3 → white
Pixel at position (240, 270):
uv = (0.8, 0.9)
center = (0.3, 0.4)
dist = sqrt(0.09 + 0.16) = 0.5 → not less than 0.3 → black
A radius of 0.3 in UV on a 300-point view is 90 points.
Smooth circle with smoothstep
Smooth Circle with smoothstep
Creates a smooth-edged circle using smoothstep for anti-aliasing
[[ stitchable ]] half4 smoothCircle(float2 position, half4 color, float2 size) {
float2 uv = position / size;
float2 center = uv - 0.5;
float dist = length(center);
float circle = 1.0 - smoothstep(0.29, 0.31, dist);
return half4(circle, circle, circle, 1.0);
}The hard-edged circle shows jagged, stair-stepped edges because each pixel is either fully in or fully out. smoothstep(edge0, edge1, x) gives a soft transition instead:
- it returns 0 when
xis at or belowedge0, - it returns 1 when
xis at or aboveedge1, - in between, it rises along an S-shaped curve.
For the circle above:
dist smoothstep(0.29, 0.31, dist) circle = 1 - that
0.25 0.0 1.0 (white)
0.295 0.16 0.84
0.30 0.5 0.5 (gray)
0.305 0.84 0.16
0.35 1.0 0.0 (black)
smoothstep is 0 inside and 1 outside, so 1.0 - flips it to get a white disc on black. The width of the blend band (0.02 in UV, so 6 points on a 300-point view) controls how soft the edge looks. Chapter 4 looks at smoothstep in more detail.
Pattern creation
Grid pattern
Grid Pattern
Creates an 8x8 grid pattern using fract() and line width detection
[[ stitchable ]] half4 gridPattern(float2 position, half4 color, float2 size) {
float2 uv = position / size;
// Create 8x8 grid
float2 grid = fract(uv * 8.0);
// Draw lines at grid boundaries
float lineWidth = 0.1;
float lines = 0.0;
if (grid.x < lineWidth || grid.y < lineWidth) {
lines = 1.0;
}
return half4(lines, lines, lines, 1.0);
}Two steps make the grid:
uv * 8.0stretches the 0 to 1 range to 0 to 8, so the view now spans eight units each way.fract()keeps only the fractional part of a number:fract(2.4) = 0.4,fract(5.97) = 0.97. Applied to the stretched coordinates, it restarts at 0 every time you cross a whole number, so each of the 64 cells gets its own 0 to 1 coordinate.
A pixel is part of a line when it's in the first 10% of its cell horizontally or vertically. On a 300-point view:
Pixel at position (100, 10):
uv * 8 = (2.67, 0.27)
fract(...) = (0.67, 0.27) → neither below 0.1 → black
Pixel at position (77, 10):
uv * 8 = (2.05, 0.27)
fract(...) = (0.05, 0.27) → x below 0.1 → white (a vertical line)
Each cell is 300 / 8 = 37.5 points wide and each line is 10% of that, 3.75 points. The lines sit on the left and top edge of every cell, so the right and bottom edges of the view have no closing line.
Radial pattern
Radial Pattern
Creates concentric circles using sin() based on distance from center
[[ stitchable ]] half4 radialPattern(float2 position, half4 color, float2 size) {
float2 uv = position / size;
float2 center = uv - 0.5;
float dist = length(center);
float pattern = sin(dist * 20.0) * 0.5 + 0.5;
return half4(pattern, pattern, pattern, 1.0);
}sin() oscillates between -1 and 1. Feeding it the distance from the center makes the value go up and down as you move outward, so pixels at the same distance share a shade and you get rings.
dist * 20.0sets how fast it oscillates. One full cycle ofsintakes 2π ≈ 6.28, so a new ring starts every 6.28 / 20 ≈ 0.31 UV units.* 0.5 + 0.5remaps -1 to 1 into 0 to 1, because color channels below 0 just show as black. -1 becomes 0, 0 becomes 0.5 and 1 becomes 1.
At the very center dist = 0 and sin(0) = 0, so the center is mid gray (0.5). Chapter 4 covers sine waves properly.
Common pitfalls
Pitfall 1: forgetting the UV transform
// Centered, but still in points: a threshold of 0.3 here means 0.3 points
float2 center = position - size * 0.5;
// Normalized first: 0.3 means 30% of the view
float2 uv = position / size;
float2 center = uv - 0.5;
The first version isn't broken. It centers the coordinates, but they stay in points, so any number you compare against has to be in points too. Copy a radius of 0.3 from a UV-based shader into it and you get a circle a third of a point wide, which looks like nothing at all. Pick one unit per shader and keep every threshold in that unit.
Pitfall 2: aspect ratio
// WRONG - Circles become ellipses on non-square views
float dist = length(uv - 0.5);
// CORRECT - Account for aspect ratio
float2 uv = position / size;
float aspectRatio = size.x / size.y;
float2 centered = (uv - 0.5) * float2(aspectRatio, 1.0);
float dist = length(centered);
This is Step 3 in code. Multiplying by float2(aspectRatio, 1.0) scales only the x component. On a 300 × 200 view aspectRatio is 1.5, x now runs from -0.75 to 0.75 and y from -0.5 to 0.5, and one unit means the same number of points on both axes.
Pitfall 3: hard edges
// WRONG - Jagged edges
float circle = step(0.3, dist);
// CORRECT - Smooth edges
float circle = smoothstep(0.29, 0.31, dist);
step(edge, x) returns 0 when x is below edge and 1 otherwise, with nothing in between. That's the same hard cut the if statement made in the first circle. smoothstep adds the blend band that hides the stair steps.
SwiftUI integration
To test your shaders, use this SwiftUI template:
struct ShaderTestView: View {
var body: some View {
Rectangle()
.frame(width: 300, height: 300)
.visualEffect { content, proxy in
content.colorEffect(
ShaderLibrary.yourShaderName(.float2(proxy.size))
)
}
}
}
Put .visualEffect after .frame so that proxy.size is the 300 × 300 frame. These shaders ignore the incoming color and compute everything from position, so it doesn't matter what the Rectangle is filled with. In the Xcode project, MetalCanvasView (in Utils/Utils.swift) wraps this same pattern: it applies .visualEffect to a 300 × 300 view and gives your closure the GeometryProxy, which is why every Chapter 2 example passes .float2(geometryProxy.size).
Challenges
Challenge 1: Basic gradients



Create three gradient shaders:
verticalGradient: black at the top, white at the bottom.diagonalGradient: black in the top-left corner, white in the bottom-right. You need a single number that is 0 atuv = (0, 0)and 1 atuv = (1, 1), built from both components.radialGradient: white in the center, fading to black toward the edges. Start from the distance to the center and flip it so that small distances are bright.
SwiftUI test code:
VStack {
Rectangle()
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.verticalGradient(.float2(proxy.size)))
}
Rectangle()
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.diagonalGradient(.float2(proxy.size)))
}
Rectangle()
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.radialGradient(.float2(proxy.size)))
}
}
.frame(width: 200, height: 200)
Here the .frame applies to the whole VStack, so each Rectangle gets a third of the height and proxy.size reports that smaller, non-square size. That's fine for the gradients, which are meant to stretch with the view.
Challenge 2: Shape drawing



Create these shape shaders:
smoothCircle: a circle with smooth edges, radius about 0.2 to 0.25.ring: a circle with a hole in the middle.square: a filled square in the center with smooth edges.
Hint for ring: draw two smooth circles, an outer one and a slightly smaller inner one, and subtract the inner from the outer. Inside the hole both are 1, so the result is 0; in the band between them only the outer one is 1.
Hint for square: a circle tests "is the straight-line distance small enough?". A square asks "are both the horizontal and the vertical distance small enough?", which is the same as checking that the larger of abs(center.x) and abs(center.y) is below the half-width.
Challenge 3: Pattern creation



Create these pattern shaders:
checkerboard: an 8 × 8 checkerboard.stripes: horizontal stripes.concentricCircles: rings spreading out from the center.
Hint for checkerboard: fract() tells you where you are inside a cell; floor(uv * 8.0) tells you which cell you're in, as whole numbers from 0 to 7. Add the column and row numbers: the sum alternates between even and odd from one cell to the next, so fmod(sum, 2.0) gives 0 or 1. Cell (2, 3) has sum 5, which is odd, so it's white.
Hint for stripes: horizontal stripes change as you move down, so they depend only on uv.y. The radial pattern above is a good starting point; replace the distance with uv.y.
Challenge 4: Interactive spotlight

Create a spotlight shader that takes the light's position as a parameter:
[[ stitchable ]] half4 spotlight(
float2 position,
half4 color,
float2 size,
float2 lightCenter // UV coordinates (0-1)
) {
// Your code here
}
lightCenter is in UV, so normalize position first and measure the distance between the two with distance(uv, lightCenter), which is the same as length(uv - lightCenter). Then turn that distance into brightness that falls off smoothly, bright at the light and dark far away.
SwiftUI integration:
struct SpotlightView: View {
@State private var lightPos = CGPoint(x: 0.5, y: 0.5)
var body: some View {
GeometryReader { geo in
Rectangle()
.visualEffect { [lightPos] content, proxy in
content.colorEffect(ShaderLibrary.spotlight(
.float2(proxy.size),
.float2(Float(lightPos.x), Float(lightPos.y))
))
}
.gesture(
DragGesture().onChanged { value in
lightPos = CGPoint(
x: value.location.x / geo.size.width,
y: value.location.y / geo.size.height
)
}
)
}
.frame(width: 300, height: 300)
}
}
The drag gesture reports its location in points, and dividing by the view size converts it to UV on the Swift side, the same normalization the shader does. The [lightPos] capture list copies the current value into the visualEffect closure. That closure is @Sendable, so with strict concurrency checking you can't read the view's @State from inside it directly.
Challenge 5: Coordinate transformations

Create rotatingPattern, which rotates a pattern over time:
[[ stitchable ]] half4 rotatingPattern(
float2 position,
half4 color,
float2 size,
float time
) {
// Rotate coordinates, then create pattern
}
To rotate a point p by an angle (in radians) around the origin:
rotated.x = p.x * cos(angle) - p.y * sin(angle)
rotated.y = p.x * sin(angle) + p.y * cos(angle)
Check it with a 90° turn (angle = π/2, so cos = 0 and sin = 1). The point (0.25, 0), to the right of the origin, becomes (0, 0.25), which is below the origin because y grows downward. A positive angle turns points clockwise on screen.
The rotation pivots around (0, 0), so rotate centered coordinates (uv - 0.5), not raw UV, or the pattern will swing around the top-left corner. Use time as the angle, then build any pattern from the rotated coordinates, for example sin(rotated.x * 10.0) * sin(rotated.y * 10.0) remapped to 0 to 1. The Xcode solution draws on a 300 × 120 view, so this is also a good place to try the aspect-ratio correction from Step 3.
SwiftUI animation:
struct RotatingPatternView: View {
@State private var startDate = Date()
var body: some View {
TimelineView(.animation) { timeline in
let time = Float(timeline.date.timeIntervalSince(startDate))
Rectangle()
.visualEffect { content, proxy in
content.colorEffect(ShaderLibrary.rotatingPattern(
.float2(proxy.size),
.float(time)
))
}
}
}
}
TimelineView(.animation) re-evaluates its content every frame, and time is the number of seconds since the view appeared. Using the elapsed time keeps the number small. Passing something like Date().timeIntervalSinceReferenceDate directly would hand the shader a value around 800 million, where a 32-bit Float can only step in increments of about a minute, and the animation would freeze. Chapter 9 covers animation timing in depth.
Want the Challenges Solutions?
Get the full Xcode project with solutions to all challenges, bonus examples, and clean, runnable code.
Get the Full Project →Validation Questions
Before proceeding to Chapter 3:
- What does
position / sizeaccomplish, and where doessizecome from?
It converts position, which is in points from (0, 0) to (width, height), into UV coordinates from (0, 0) to (1, 1), so the same numbers describe the same relative place on any view: 0.5 is always halfway. size isn't provided by colorEffect. You pass it yourself, usually as .float2(proxy.size) from .visualEffect, and it's in points too, so the division is consistent.
- What are the UV coordinates of the center of any view?
(0.5, 0.5), for any size or aspect ratio.
- How do you create a smooth circle edge?
Replace the hard comparison with smoothstep(). 1.0 - smoothstep(0.29, 0.31, dist) is 1 inside radius 0.29, 0 outside radius 0.31, and blends between them, which hides the jagged pixel steps.
- Why use
length(uv - 0.5)for distance from center?
uv - 0.5 moves the origin to the center of the view, so the result is the pixel's offset from the center. length() turns that offset into a straight-line distance, sqrt(x² + y²).
- What's the difference between
step()andsmoothstep()?
step(edge, x) jumps straight from 0 to 1 at edge. smoothstep(edge0, edge1, x) rises gradually from 0 to 1 between its two edges. The hard jump produces jagged, aliased edges; the gradual one smooths them.
- On a 400 × 200 view you draw a circle with
length(uv - 0.5)less than 0.25. What do you actually see, and how do you fix it?
An ellipse. Horizontally the edge is 0.25 × 400 = 100 points from the center, vertically 0.25 × 200 = 50 points, so it's 200 points wide and 100 points tall. Multiply the centered x by the aspect ratio, 400 / 200 = 2, before taking the length. The radius then means 0.25 × 200 = 50 points in both directions.
Essential Functions to Remember
// Coordinate transformation
float2 uv = position / size;
// Distance from center
float dist = length(uv - 0.5);
// Smooth transitions
float smooth = smoothstep(edge1, edge2, value);
// Grid creation
float2 grid = fract(uv * gridSize);
// Rotation (apply to centered coordinates so it pivots around the middle)
float2 rotated = float2(
uv.x * cos(angle) - uv.y * sin(angle),
uv.x * sin(angle) + uv.y * cos(angle)
);
Next Chapter Preview: Everything in this chapter was grayscale and ignored the color parameter. Chapter 3 puts color to work: you'll treat colors as vectors you can scale, add and blend with mix, convert to HSV to change hue and saturation, compute perceived brightness for grayscale and sepia, and learn how SwiftUI's premultiplied alpha affects all of it.