The color parameter you've been ignoring
Every shader in Chapter 2 had this signature:
half4 shader(float2 position, half4 color, float2 size)
and none of them used color. They generated an image from position alone, so whatever the view looked like underneath was thrown away.
color is the view's own color at this pixel, before your shader runs. Attach .colorEffect to an Image and color is the photo's pixel; attach it to Text and it's the text color where there are glyphs and fully transparent everywhere else. If your shader just does return color; (the passthrough example in the Xcode project), the view looks unchanged. Everything in this chapter starts from that color and changes it: brighter, grayer, warmer, a different hue.
Colors are vectors
A half4 color is four numbers, (r, g, b, a), usually between 0 and 1. Metal treats it like any other vector, so arithmetic works on all four components at once, and each kind of operation has a visual meaning:
- Multiplying the RGB part by a number below 1 darkens; above 1 brightens.
- Adding to the RGB part lifts every channel, which brightens and washes out.
1.0 - rgbinverts.mixblends two colors.
The .rgb swizzle lets you work on the color channels and leave alpha alone, which you'll do in almost every effect. To see why, you first need to know how SwiftUI stores alpha.
Premultiplied alpha
SwiftUI hands your shader colors with premultiplied alpha: the red, green and blue values have already been multiplied by alpha. It also expects you to return colors in the same form.
Straight color (what you'd pick in a color picker): white at 50% opacity = (1.0, 1.0, 1.0) at alpha 0.5
Premultiplied (what the shader sees): (1.0 × 0.5, 1.0 × 0.5, 1.0 × 0.5, 0.5) = (0.5, 0.5, 0.5, 0.5)
Two consequences you'll run into constantly:
- In a valid premultiplied color, no RGB channel is larger than alpha. A fully transparent pixel is always
(0, 0, 0, 0). half4(1.0, 1.0, 1.0, 0.5)is not 50% transparent white. It breaks rule 1, and SwiftUI composites it as if it were brighter than white, so it shows up as a glowing, almost additive patch. 50% white ishalf4(0.5, 0.5, 0.5, 0.5).
Values passed in with .color(...) from Swift arrive premultiplied too. For fully opaque content (a = 1), premultiplied and straight are the same numbers, which is why plenty of shaders get away with ignoring this until they meet a transparent edge.
Mathematical foundation
Color operations
Using one example color, a brownish orange:
half4 c = half4(0.8, 0.4, 0.2, 1.0); // Brownish orange, opaque
c * 0.5 // Scales alpha too: (0.4, 0.2, 0.1, 0.5) is c at 50% opacity
half4(c.rgb * 0.5, c.a) // Darken by 50%: (0.4, 0.2, 0.1, 1.0)
half4(c.rgb + 0.2, c.a) // Brighten: (1.0, 0.6, 0.4, 1.0); larger additions go above 1.0
half4(c.a - c.rgb, c.a) // Invert: (0.2, 0.6, 0.8, 1.0); a - rgb also works when alpha < 1
The first two lines show why .rgb matters. c * 0.5 multiplies all four channels, and in premultiplied form halving everything is exactly how you fade a color to 50% opacity. To darken, scale only the RGB part and keep alpha.
The inversion uses c.a - c.rgb instead of 1.0 - c.rgb. For an opaque color (a = 1) they give the same result. "Common pitfalls" below shows what happens when they don't.
The mix function
mix is linear interpolation, the most used function in graphics:
mix(a, b, t) // Returns a when t=0, b when t=1
// Equivalent to: a * (1-t) + b * t
t is how far you've moved from a toward b. Mixing opaque red (1, 0, 0, 1) and opaque green (0, 1, 0, 1):
t = 0.0 → (1.0, 0.0, 0, 1) pure red
t = 0.25 → (0.75, 0.25, 0, 1) red × 0.75 + green × 0.25
t = 0.5 → (0.5, 0.5, 0, 1) olive
t = 1.0 → (0.0, 1.0, 0, 1) pure green
The Xcode project's twoColorBlend example does exactly this with mix(start, end, uv.x), so the color slides from red on the left to green on the right. t doesn't have to come from position: it can be a slider value, a brightness, or time. You'll use mix in nearly every challenge below.
The middle color may look darker and muddier than you'd expect. The reason is in "Gamma" below.
RGB: how the hardware sees color
RGB matches the display (each pixel is a red, green and blue subpixel), the GPU can operate on it directly, and there's nothing to convert. It's a poor fit for how people describe color, though:
- Which RGB values make orange? (1.0, 0.5, 0.0), but you'd have to know that.
- To make a color "more vivid", which channels do you change, and by how much?
- To shift every color in an image toward the next hue, what do you do to R, G and B?
HSV: closer to how people describe color
HSV describes the same colors with three different numbers:
- Hue is which color it is, as an angle around a color wheel: 0° red, 60° yellow, 120° green, 180° cyan, 240° blue, 300° magenta. In shader code it's usually stored as a fraction of a full turn, 0 to 1, so 60° is 1/6 ≈ 0.167.
- Saturation is how pure it is: 0 is gray, 1 is fully vivid.
- Value is how bright it is: 0 is black, 1 is full brightness.
The conversion from RGB is simpler than the code below makes it look:
Value = the largest channel
Saturation = (largest - smallest) / largest
Hue = which channel is largest, and how the other two compare
Converting our brownish orange (0.8, 0.4, 0.2) by hand:
largest = 0.8 (red), smallest = 0.2
Value = 0.8
Saturation = (0.8 - 0.2) / 0.8 = 0.75
Hue = 60° × (g - b) / (largest - smallest) ← formula when red is largest
= 60° × (0.4 - 0.2) / 0.6 = 20° (0.056 as a fraction of a turn)
So it's a reddish orange (20°), fairly saturated (0.75), slightly dimmed (0.8). Now "make it more vivid" is a single change: raise saturation. "Rotate the hue" is another: add to hue. Converting there and back is what makes those edits possible.
Perceived brightness
To turn a color into gray you need one number for "how bright is this", and averaging the three channels gives the wrong answer. Your eyes are most sensitive to green and least sensitive to blue, so pure green looks much brighter than pure blue even though both are a single channel at 1.0. The standard fix is a weighted sum:
luma = 0.299 × R + 0.587 × G + 0.114 × B
The weights add up to 1, so white stays 1 and black stays 0. Comparing with a plain average:
plain average luma
pure red (1,0,0) 0.333 0.299
pure green (0,1,0) 0.333 0.587
pure blue (0,0,1) 0.333 0.114
(0.8, 0.4, 0.2) 0.467 0.299×0.8 + 0.587×0.4 + 0.114×0.2 = 0.497
With the plain average, a blue sky and green grass of the same RGB strength come out the same gray. With luma weights the grass is about five times lighter than the blue, which matches what you see.
These weights (from the Rec. 601 video standard) are designed for gamma-encoded values like the ones SwiftUI gives you. You'll also see 0.2126, 0.7152, 0.0722 (Rec. 709); those are meant for linear values, which the next section explains.
Gamma: sRGB versus linear values
Apple's documentation for Shader says colors are in the destination's color space, typically extended sRGB. sRGB values are gamma-encoded: the numbers are spaced to match how we perceive brightness, not the amount of light. A channel value of 0.5 is perceptually about halfway, but the screen emits only about 21% of the light of 1.0. ("Extended" means wide-gamut colors, such as Display P3, can have channels below 0 or above 1.)
For this chapter's effects, working on the encoded values directly is normal and looks fine. It explains two things you'll notice:
mixbetween two bright colors can produce a darker, muddier middle, like the olive between red and green above, because averaging encoded values doesn't average the light.- Physically based effects (realistic light, blur and glow that add up light) are usually computed on linear values: convert from sRGB to linear, do the maths, convert back.
You don't need linear maths yet. Know that it exists for when a blend looks too dark.
Your first image processing shader
Brighten Shader
Increases brightness by 20% while preserving alpha channel
[[ stitchable ]] half4 brighten(float2 position, half4 color, float2 size) {
// Increase brightness by 20%
return half4(color.rgb * 1.2, color.a);
}Three things to notice:
- It reads the incoming
colorinstead of generating a color from position. - It scales only the RGB part, so the image keeps its transparency.
- Bright channels can go past 1.0: 0.9 × 1.2 = 1.08. On a standard display those values are clipped to full brightness, so the brightest parts of the image lose detail. That's acceptable for a 20% boost; for larger ones, see Pitfall 2.
Multiplication suits brightening better than addition because it keeps black at black (0 × 1.2 = 0) and preserves the ratios between channels, so hues don't shift.
Common pitfalls
Pitfall 1: forgetting alpha premultiplication
// WRONG - Ignores how alpha affects color
return half4(color.rgb + 0.5, color.a);
// CORRECT - Respects transparency
return half4(color.rgb + 0.5 * color.a, color.a);
Because the incoming color is premultiplied, whatever you add has to be premultiplied as well. Follow two pixels through both versions:
Fully transparent pixel (0, 0, 0, 0):
WRONG → (0.5, 0.5, 0.5, 0) RGB above alpha: invalid, shows as a glow
CORRECT → (0, 0, 0, 0) still invisible
50% transparent dark gray, straight (0.2, 0.2, 0.2) → premultiplied (0.1, 0.1, 0.1, 0.5):
WRONG → (0.6, 0.6, 0.6, 0.5) invalid again
CORRECT → (0.35, 0.35, 0.35, 0.5) = straight (0.7, 0.7, 0.7) at 50%: lighter, same transparency
The wrong version makes the transparent area around text or a shape light up. The correct one can still push a bright channel above alpha (a premultiplied red of 0.5 at alpha 0.5 would become 0.75), so for large additions combine it with the cap from Pitfall 2.
Pitfall 2: creating invalid colors
// WRONG - Can produce values > 1.0, and doubles alpha too
half4 brightened = color * 2.0;
// CORRECT - Scale RGB only, and keep each channel at or below alpha
half4 brightened = half4(min(color.rgb * 2.0, color.a), color.a);
// For opaque content, letting the display clip values above 1.0 is often fine
color * 2.0 doubles alpha as well. For an opaque pixel that gives alpha 2.0, which is meaningless; for a 50% transparent one it changes the opacity. The correct version only touches RGB, and min(..., color.a) caps each channel at alpha, the brightest a premultiplied channel can be. For an opaque pixel, alpha is 1, so that's the familiar clamp to 1.0.
Pitfall 3: assuming the input is opaque
// WRONG - Assumes alpha = 1.0
return half4(1.0 - color.rgb, 1.0);
// CORRECT - Keeps the original alpha and stays valid when alpha < 1
return half4(color.a - color.rgb, color.a);
The wrong version forces every pixel opaque, so transparent regions turn into solid color (black inverts to white, so the area around your view fills with white).
Why color.a - color.rgb instead of 1.0 - color.rgb? Inverting the straight color gives 1 - rgb / a; premultiplying that again gives a - rgb. With 1.0 - color.rgb, a fully transparent pixel (0, 0, 0, 0) becomes (1, 1, 1, 0), which is invalid and glows. With color.a - color.rgb it stays (0, 0, 0, 0), and 50% white (0.5, 0.5, 0.5, 0.5) becomes (0, 0, 0, 0.5), which is 50% black, as it should be.
Color space conversions
// Simplified but functional RGB→HSV
float3 rgb2hsv(float3 c) {
float4 K = float4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
float4 p = mix(float4(c.bg, K.wz), float4(c.gb, K.xy), step(c.b, c.g));
float4 q = mix(float4(p.xyw, c.r), float4(c.r, p.yzx), step(p.x, c.r));
float d = q.x - min(q.w, q.y);
float e = 1.0e-10;
return float3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
}
// HSV→RGB
float3 hsv2rgb(float3 c) {
float4 K = float4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
float3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
}
You don't need to memorize these. They compute the same Value, Saturation and Hue as the hand calculation above, but use step and mix to pick the largest channel without if statements, which is a common GPU habit. Both return and accept float3(hue, saturation, value) with every component from 0 to 1. The e = 1.0e-10 avoids dividing by zero for black and grays. Paste them above your shaders in the .metal file and call them like any other function.
Here's what they make possible:
Saturate Shader
Increases color saturation by 50% using RGB↔HSV conversion
[[ stitchable ]] half4 saturate(float2 position, half4 color, float2 size) {
float3 hsv = rgb2hsv(float3(color.rgb));
hsv.y = clamp(hsv.y * 1.5, 0.0, 1.0); // Increase saturation by 50%
return half4(half3(hsv2rgb(hsv)), color.a);
}The helpers work on float3, and Metal doesn't convert between half3 and float3 automatically, so the shader converts explicitly on the way in (float3(color.rgb)) and on the way out (half3(...)).
Following our brownish orange through it:
rgb (0.8, 0.4, 0.2)
→ hsv (20°, 0.75, 0.8)
→ saturation × 1.5 = 1.125, clamped to 1.0
→ hsv (20°, 1.0, 0.8)
→ rgb (0.8, 0.267, 0.0)
Same hue, same brightness, more vivid: the blue channel drops to 0 and green moves away from red. Grays have saturation 0, and 0 × 1.5 is still 0, so neutral areas of the image stay neutral.
Visual explanation
RGB as a cube
Each channel is one axis, so every color is a point inside a unit cube:
B-----------M
/| /|
/ | / |
C-----------W |
| | | |
| K--------|--R
| / | /
|/ |/
G-----------Y
K black (0,0,0) R red (1,0,0) G green (0,1,0) B blue (0,0,1)
Y yellow (1,1,0) C cyan (0,1,1) M magenta (1,0,1) W white (1,1,1)
Red runs to the right, green toward you and blue upward. The diagonal from black (K) to white (W) holds every gray, where r = g = b. mix(a, b, t) moves along the straight line between two points in this cube.
HSV as a cylinder
Looking down at the hue wheel from the top of the cylinder:
Red (0°)
Magenta (300°) Yellow (60°)
Blue (240°) Green (120°)
Cyan (180°)
Hue: angle around the wheel
Saturation: distance from the center (center = gray, rim = pure hue)
Value: height of the cylinder (bottom = black, top = full brightness)
Adding 120° to the hue moves every color two steps clockwise on this wheel: red to green, green to blue, blue to red.
Challenges
The Xcode project shows each solution on an image (with a picker to switch between two photos), so you can see the effect on real content.
Challenge 1: Basic color filters



Create these shaders:
grayscale: convert to gray using the luma weights from "Perceived brightness" (0.299R + 0.587G + 0.114B) and put the result in all three channels.sepia: an old-photo brown tone. Compute the gray, thenmixit with a brown such as(112, 66, 20) / 255.invert: invert the colors while preserving alpha.
Writing the gray calculation as a small helper function (the solution calls it toGray) lets you reuse it in the later challenges.
Challenge 2: Selective color modification

Create redBoost that:
- multiplies the red channel by 1.5,
- only for pixels whose red is already above 0.5,
- and leaves every other pixel unchanged.
A pixel with red 0.8 becomes 1.2 and clips to full red. Notice the visible edge where red crosses 0.5: the boost switches on all at once. As an extra, try replacing the if with a smoothstep around 0.5 and mix between the original and boosted color, so the change fades in.
Challenge 3: Color temperature

Create temperature that:
- takes a
float temperatureparameter from -1 to 1 (the Xcode project drives it with aSlider), - tints the image toward blue (cold) for negative values,
- and toward orange (warm) for positive values.
Hint: (temperature + 1) / 2 maps -1…1 to 0…1, which you can use as the t of a mix between blue and orange. Then mix the original color toward that tint.
Going further: with the approach above, 0 still tints the image, with a 50/50 blend of blue and orange. Make 0 leave the image unchanged by using abs(temperature) as the strength of the tint. Then preserve luminance: compute the luma before and after tinting and scale the RGB by before / after, so the tint changes color without making the image brighter or darker.
Challenge 4: Hue rotation

Create hueRotate that:
- takes a
float amountparameter in degrees, 0 to 360 (aSliderin the Xcode project), - rotates every hue by that amount,
- and keeps saturation and value unchanged.
At 120°, reds become greens, greens become blues and blues become reds.
Hint: convert to HSV, add amount / 360 to the hue (the hue is stored as a fraction of a turn), convert back. You don't need to wrap the hue yourself: hsv2rgb uses fract internally, so a hue of 1.2 behaves like 0.2.
Challenge 5: Gradient mapping

Create duoTone that:
- converts the input to gray,
- pushes dark tones toward a deep blue and bright tones toward a bright orange,
- for a two-color, poster-like look.
The simplest version (the one in the Xcode solution) checks whether the gray is below 0.5 and mixes it with blue, otherwise with orange. That gives a hard split between the two tints. A true gradient map is a single line, mix(deepBlue, brightOrange, gray): black maps to blue, white to orange and every gray in between to a blend. Try both and compare.
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 4:
- What happens when you add
half4(0.5, 0.5, 0.5, 0.5)to a color?
All four channels go up by 0.5. RGB gets brighter and can pass 1.0, which is clipped on a standard display. Alpha goes up too: an opaque pixel would reach 1.5 (meaningless, effectively still 1), and a fully transparent pixel (0, 0, 0, 0) becomes (0.5, 0.5, 0.5, 0.5), which is 50% white appearing where there was nothing. To brighten without touching transparency, add to .rgb only and premultiply what you add, as in Pitfall 1.
- Why might
color * 2.0produce unexpected results?
It multiplies alpha as well as RGB, which changes the opacity of any semi-transparent pixel. And the RGB values can go above 1.0, so highlights clip to pure white and lose detail. Scale .rgb only and cap it, as in Pitfall 2.
- How would you make a color 50% transparent?
Because SwiftUI colors are premultiplied, multiply all four channels by 0.5: color * 0.5. For an opaque input that gives exactly 50% opacity. half4(color.rgb, 0.5) is wrong: for opaque white it produces (1, 1, 1, 0.5), where RGB exceeds alpha, and it renders brighter than intended. Note that color * 0.5 halves whatever opacity the pixel already had; a pixel at 80% ends up at 40%.
- What's the HSV representation of pure yellow?
Hue = 60° (1/6 ≈ 0.167 as a fraction of a turn), Saturation = 1.0, Value = 1.0. Yellow is (1, 1, 0): the largest channel is 1 (value), the smallest is 0 so saturation is (1 - 0) / 1 = 1, and red and green being equal puts it exactly between red (0°) and green (120°).
- Why preserve the original alpha in most effects?
Alpha defines the shape of the content: where text, an icon or a photo's edges are, and how they blend with what's behind them. If a color effect changes alpha, transparent areas can turn solid or glow, and edges stop compositing correctly. Change .rgb, keep color.a, and keep every RGB channel at or below alpha.
Debugging Tip
Visualize individual channels:
return half4(color.r, 0, 0, 1); // Red channel only
return half4(color.a, color.a, color.a, 1); // Alpha as grayscale
Both return an opaque color, so you see the channel's value as brightness everywhere, including in transparent areas. The alpha view is the quickest way to check where your view is actually transparent. Keep in mind that color.r is premultiplied, so semi-transparent pixels show darker in the red view than they look on screen.
Further Exploration
- Color theory: complementary colors sit 180° apart on the hue wheel. Try generating a complementary tint with
hueRotate. - Perception: the luma weights are one model of brightness. Look up perceptual color spaces such as CIELAB and Oklab, which also aim for even steps in hue and saturation.
- Linear workflows: try converting to linear before a
mixand back afterwards, and compare the midpoint with the gamma-encoded version. - HDR: what happens beyond the 0 to 1 range, and how extended sRGB represents colors brighter than white.
Next Chapter Preview: You can now generate color from position and modify existing colors. Chapter 4 introduces the functions that create patterns: sin, cos, fract, and more. You'll create waves, pulses, and rhythms that bring static shaders to life.