skip to content

In SwiftUI on iOS 17 and later, how do colorEffect, distortionEffect and layerEffect apply a Metal shader, and why does layerEffect need maxSampleOffset?

level: seniorimportance: nice to knowfreq 25%

answer

  1. stitchable Metal function per pixel
  2. colour, position, or the layer
  3. ShaderLibrary dynamic member lookup
  4. how far a sample may stray

basics

~20 s

Each modifier runs a [[ stitchable ]] Metal function from a ShaderLibrary per pixel: colorEffect recolours one pixel, distortionEffect returns where to read from, layerEffect samples the rasterized view freely. maxSampleOffset declares how far reads may stray from each pixel.

solid answer

~40 s

All three take a `Shader`, usually `ShaderLibrary.default.<function>(arguments)`, which looks the function up by name in the app's Metal library and binds uniforms such as `.float(_:)`, `.color(_:)` or `.boundingRect`. The function must be `[[ stitchable ]]` with a fixed leading signature: `colorEffect` gets `(float2 position, half4 color, …)` and returns a colour; `distortionEffect` gets `(float2 position, …)` and returns the source position to read; `layerEffect` gets `(float2 position, SwiftUI::Layer layer, …)` and may call `layer.sample(...)` anywhere. Because distortion and layer effects read pixels other than their own, both require `maxSampleOffset:`, the furthest a read may be from the destination in each axis; Apple's documentation says it must cover every sample, and it has no default. Views backed by UIKit may render as placeholders.

code

swift · 27 lines
swift
import SwiftUI

struct PrivacyBlurredPhoto: View {
    var cellSize: Double          // points per block; 1 means no visible effect
    var isHidden: Bool

    var body: some View {
        Image("finish-line")
            .resizable()
            .scaledToFill()
            .frame(width: 300, height: 200)
            .clipped()
            .layerEffect(
                ShaderLibrary.default.pixellate(.float(cellSize)),
                maxSampleOffset: CGSize(width: cellSize / 2, height: cellSize / 2),
                isEnabled: isHidden
            )
    }
}

struct DimmedBadge: View {
    var body: some View {
        Image(systemName: "figure.run.circle.fill")
            .font(.system(size: 64))
            .colorEffect(ShaderLibrary.default.desaturate(.float(0.8)))
    }
}

go deeper

for a junior

Recall that SwiftUI can apply a Metal function to a view's pixels from iOS 17, through colorEffect, distortionEffect and layerEffect.

for a middle

Explain the stitchable signatures, what each modifier's function receives and returns, and how ShaderLibrary and Shader.Argument bind the call.

for a senior

Show you size maxSampleOffset from the shader's maths, handle placeholders, platforms, isEnabled toggling and first-use compilation, and respect Reduce Motion.

for a principal

Judge where custom shaders earn their maintenance cost in a product, who owns the Metal code, and how effects degrade on older OS versions and with accessibility settings.

## Shaders as SwiftUI modifiers Since **iOS 17**, SwiftUI can run a Metal shader function over a view's pixels with three view modifiers. A **shader** here is a small function written in the Metal Shading Language (MSL) in a `.metal` file in your target; SwiftUI calls it once per pixel on the GPU. The Swift side is a `Shader` value: a reference to a function in a `ShaderLibrary` plus the uniform arguments bound to it. None of these types is available on watchOS. You get a `Shader` by dynamic member lookup: `ShaderLibrary.default.pixellate(.float(8))` finds the function named `pixellate` in the default library and binds one float argument. `Shader.Argument` includes `.float`, `.float2` to `.float4`, `.floatArray`, `.color`, `.colorArray`, `.image`, `.data` and `.boundingRect`, the last of which passes the view's bounds. ## The three signatures Each modifier requires the MSL function to be marked `[[ stitchable ]]` and to start with a fixed set of parameters; your own arguments follow. | Modifier | Leading MSL parameters | Returns | `maxSampleOffset` | |---|---|---|---| | `colorEffect(_:isEnabled:)` | `float2 position, half4 color` | the new colour | none | | `distortionEffect(_:maxSampleOffset:isEnabled:)` | `float2 position` | the source position to read | required | | `layerEffect(_:maxSampleOffset:isEnabled:)` | `float2 position, SwiftUI::Layer layer` | a colour, usually from `layer.sample(...)` | required | - **colorEffect** sees one pixel's premultiplied colour and returns a new one: tints, desaturation, thresholds. - **distortionEffect** never sees colours; it returns where the destination pixel should be read from: ripples, waves, bulges. - **layerEffect** gets the rasterized view as a `SwiftUI::Layer` and may sample it anywhere: pixellation, blurs, chromatic offsets. `SwiftUI::Layer` is declared in `<SwiftUI/SwiftUI.h>` and exports one function, `sample(float2)`, which returns a linearly filtered premultiplied pixel. A `Shader` also conforms to `ShapeStyle`, so `fill(_:)` accepts one whose function has the shape `half4 name(float2 position, args...)`. ## Wiring one up 1. Add a `.metal` file to the app target, so Xcode builds it into the app's default Metal library. 2. Include `<metal_stdlib>` and, for layer effects, `<SwiftUI/SwiftUI.h>`. 3. Write the function with `[[ stitchable ]]` and the leading parameters its modifier expects. 4. In Swift, build the shader from `ShaderLibrary.default` (or `ShaderLibrary.bundle(_:)` for another bundle) and apply the modifier. ```metal #include <metal_stdlib> #include <SwiftUI/SwiftUI.h> using namespace metal; [[ stitchable ]] half4 pixellate(float2 position, SwiftUI::Layer layer, float size) { float2 cell = floor(position / size) * size + size * 0.5; return layer.sample(cell); } ``` ## Why maxSampleOffset exists A colour effect touches only the pixel it is given. Distortion and layer effects read **other** pixels, so SwiftUI asks you up front for the furthest distance a read can be from its destination pixel, in each axis, as a `CGSize`. Apple's documentation for `layerEffect` says that whenever the function samples at locations other than the destination, this value **must** specify the maximum sampling distance. The parameter has no default: leaving it out is a compile error, "missing argument for parameter 'maxSampleOffset' in call". Compute it from the shader's maths. The pixellate function above reads the centre of a cell, never more than half a cell from the destination, so `CGSize(width: size / 2, height: size / 2)` is exact. An offset smaller than what the shader actually reads breaks that documented contract. ## Production concerns - **isEnabled** turns the effect off while the modifier stays in place, rather than branching between two view structures. - **UIKit-backed content**: per Apple's documentation, views backed by UIKit or AppKit may not render into the filtered layer; they log a warning and show a placeholder. - **Geometry**: the three effects also exist on `VisualEffect`, so inside `visualEffect(_:)` you can feed the proxy's size to a shader. - **First use**: iOS 18 added `Shader.compile(as:)`, an async throwing method that compiles a shader for a usage type such as `.layerEffect` ahead of time. - **Accessibility**: a moving distortion should respect `accessibilityReduceMotion`, and an effect that hides content must not be the only signal of state. - **Platforms**: watchOS has no shader effects, so shared code needs an alternative there. ## Mistakes the compiler cannot see Two classes of bug pass the Swift build and only show when the shader runs: - `ShaderLibrary` uses string-based dynamic member lookup, so a misspelled function name such as `ShaderLibrary.default.pixelate` compiles even when the Metal function is called `pixellate`. - The arguments you bind must match, in order and type, the parameters after the leading ones; binding `.float2(...)` to a `float` parameter is not checked by Swift. A preview or a snapshot test that renders each effect once is the cheapest place to notice either before review.

  • How do you use a shader as a fill rather than a filter?
    `Shader` conforms to `ShapeStyle`, so `Rectangle().fill(ShaderLibrary.default.stripes(.float(8), .color(.mint)))` works. The MSL function then has the signature `[[ stitchable ]] half4 name(float2 position, args...)`: it receives each pixel's user-space position and returns a premultiplied colour, with no source colour or layer to read.
  • Why might a shader effect show a placeholder instead of the view?
    Apple's documentation for each effect warns that views backed by UIKit or AppKit may not render into the filtered layer; they log a warning and display a placeholder. A map, web view or wrapped UIKit control inside the modified subtree is the usual cause. Apply the effect to SwiftUI-drawn content only.
  • How do you pass a view's size to a shader?
    Bind `.boundingRect` as an argument, which hands the shader the view's bounds, or apply the effect inside `visualEffect(_:)`, where `colorEffect`, `distortionEffect` and `layerEffect` are also available on the `VisualEffect` placeholder and the closure's `GeometryProxy` supplies the size for `.float2(_:)`.

  • colorEffect can move pixels to create a ripple
  • maxSampleOffset is optional and defaults to zero
  • A layerEffect renders maps and web views like any other content
  • Shader effects work on every platform SwiftUI supports, watchOS included
  • Any Metal function works as long as it is in a .metal file

Assumes the iOS 27 SDK; Shader, ShaderLibrary and the three effect modifiers arrived in iOS 17 (not on watchOS), and Shader.compile(as:) in iOS 18.