Keep Pinch Zoom Anchored In A SwiftUI Diagram

The first pinch looks fine. Then you lift your fingers, pinch somewhere else, and the diagram jumps. The second pinch should not relocate the thing you just found.

A scale and a newly assigned anchor are not enough to describe the view’s existing position. Keep a scale and a translation, then calculate the next transform from the content point beneath the new pinch.

We will build a small diagram inspector for iOS 17 or later, using the current Swift 6.4 compiler. It supports repeated anchored pinches, bounded zoom, point selection, and ordinary Zoom In, Zoom Out, and Reset buttons. It deliberately does not implement dragging, inertia, rotation, or simultaneous pan-and-pinch behavior. To inspect a different region, Reset and pinch there. For a photo viewer that needs standard scrolling physics, a UIScrollView bridge remains a sensible choice.

The long-running Stack Overflow zoom question already has working approaches, including UIKit bridges. A more specific anchor question also has an answer pointing to iOS 17’s MagnifyGesture. This is not a newly unlocked OS 27 capability. The useful work is connecting that API to a repeatable coordinate model and testing the awkward second gesture.

Download the complete sample and tests. The Swift blocks below fit together, in order, in one iOS app file. Replace the generated App declaration with the final block.

Give every point an address

Use content coordinates for the diagram and viewport coordinates for touches:

viewportPoint = contentPoint × scale + translation
contentPoint  = (viewportPoint − translation) / scale

Suppose a pinch starts at viewport point a. Invert the current transform to find the content point c under it. After choosing the new scale s, the translation must be a − c × s. That preserves the point beneath the gesture’s starting location. It does not track a moving two-finger centroid.

Mihaela Mihaljević Jakić’s Modifier Order Is Matrix Order is useful inspiration here: treat transform order as a decision, not a sequence of experiments until the picture looks plausible. Our implementation applies a top-leading scale, then a viewport-space offset. Apple’s scale effect and offset documentation also distinguish rendered movement from layout size. Neither modifier creates a larger layout slot for the zoomed content.

import SwiftUI

nonisolated struct DiagramTransform: Equatable {
    let scale: CGFloat
    let translation: CGPoint

    func contentPoint(at point: CGPoint) -> CGPoint {
        CGPoint(x: (point.x - translation.x) / scale,
                y: (point.y - translation.y) / scale)
    }

    func viewportPoint(for point: CGPoint) -> CGPoint {
        CGPoint(x: point.x * scale + translation.x,
                y: point.y * scale + translation.y)
    }

    func zoomed(by factor: CGFloat, around anchor: CGPoint,
                limits: ClosedRange<CGFloat>) -> Self {
        guard factor.isFinite, factor > 0,
              anchor.x.isFinite, anchor.y.isFinite else { return self }
        let nextScale = min(limits.upperBound, max(limits.lowerBound, scale * factor))
        let point = contentPoint(at: anchor)
        return Self(scale: nextScale, translation: CGPoint(
            x: anchor.x - point.x * nextScale,
            y: anchor.y - point.y * nextScale
        ))
    }

    func bounded(content: CGSize, viewport: CGSize) -> Self {
        func offset(_ proposed: CGFloat, length: CGFloat, available: CGFloat) -> CGFloat {
            if length <= available { return (available - length) / 2 }
            return min(0, max(available - length, proposed))
        }
        return Self(scale: scale, translation: CGPoint(
            x: offset(translation.x, length: content.width * scale, available: viewport.width),
            y: offset(translation.y, length: content.height * scale, available: viewport.height)
        ))
    }

    static func fit(content: CGSize, viewport: CGSize) -> Self {
        let scale = min(viewport.width / content.width, viewport.height / content.height)
        return Self(scale: scale, translation: .zero).bounded(content: content, viewport: viewport)
    }

    func selectedPoint(at location: CGPoint, content: CGSize) -> CGPoint? {
        let point = contentPoint(at: location)
        guard point.x.isFinite, point.y.isFinite,
              (0...content.width).contains(point.x),
              (0...content.height).contains(point.y) else { return nil }
        return point
    }
}

This small internal type assumes finite, positive content and viewport sizes, a positive scale, and positive ordered scale limits. The view below supplies those inputs. It is not a decoder for untrusted transform data.

Scale clamping happens before calculating translation. That preserves the anchor even when the requested zoom would exceed a scale limit. bounded, however, is a separate product policy: center an axis that fits; otherwise prevent an empty strip beyond an edge. That correction can move the anchored point. You cannot always have both a fixed anchor and fully constrained edges.

Keep the gesture on the viewport

Our drawing has a fixed 320 × 240 content space. Its center marker gives us a visible reference, and a selected point lives in that same space. Transform the drawing and selection together.

struct InspectionDiagram: View {
    let alternate: Bool
    let selected: CGPoint?

    var body: some View {
        ZStack(alignment: .topLeading) {
            Rectangle().fill(.background)
            Rectangle().fill(alternate ? .orange : .teal)
                .frame(width: 130, height: 180).position(x: 85, y: 120)
                .accessibilityLabel("West room")
            Rectangle().fill(alternate ? .purple : .blue)
                .frame(width: 130, height: 180).position(x: 235, y: 120)
                .accessibilityLabel("East room")
            Circle().fill(.yellow).frame(width: 12, height: 12)
                .position(x: 160, y: 120)
                .accessibilityLabel("Diagram center")
            if let selected {
                Circle().stroke(.red, lineWidth: 2).frame(width: 16, height: 16)
                    .position(selected)
                    .accessibilityLabel("Inspection point")
            }
        }
        .frame(width: 320, height: 240)
    }
}

struct DiagramInspector: View {
    let viewport: CGSize
    let alternate: Bool
    private let content = CGSize(width: 320, height: 240)
    @State private var committed: DiagramTransform
    @State private var selected: CGPoint?
    @GestureState private var pinch: MagnifyGesture.Value?

    init(viewport: CGSize, alternate: Bool) {
        self.viewport = viewport
        self.alternate = alternate
        _committed = State(initialValue: .fit(
            content: CGSize(width: 320, height: 240), viewport: viewport
        ))
    }

    private var fit: DiagramTransform { .fit(content: content, viewport: viewport) }
    private var limits: ClosedRange<CGFloat> { fit.scale...(fit.scale * 5) }
    private var effective: DiagramTransform {
        guard let pinch else { return committed }
        return transformed(by: pinch.magnification, around: pinch.startLocation)
    }

    private func transformed(by factor: CGFloat, around anchor: CGPoint) -> DiagramTransform {
        committed.zoomed(by: factor, around: anchor, limits: limits)
            .bounded(content: content, viewport: viewport)
    }

    private func zoom(by factor: CGFloat) {
        committed = transformed(by: factor, around: CGPoint(
            x: viewport.width / 2, y: viewport.height / 2
        ))
    }

    var body: some View {
        VStack(spacing: 12) {
            ZStack(alignment: .topLeading) {
                Color.gray.opacity(0.2)
                InspectionDiagram(alternate: alternate, selected: selected)
                    .scaleEffect(effective.scale, anchor: .topLeading)
                    .offset(x: effective.translation.x, y: effective.translation.y)
            }
            .frame(width: viewport.width, height: viewport.height, alignment: .topLeading)
            .clipped()
            .contentShape(Rectangle())
            .accessibilityElement(children: .contain)
            .accessibilityLabel("Zoomable diagram")
            .gesture(MagnifyGesture()
                .updating($pinch) { value, state, _ in state = value }
                .onEnded { value in
                    committed = transformed(by: value.magnification, around: value.startLocation)
                })
            .simultaneousGesture(SpatialTapGesture().onEnded { value in
                guard pinch == nil else { return }
                selected = committed.selectedPoint(at: value.location, content: content)
            })

            ViewThatFits(in: .horizontal) {
                HStack { controls }
                VStack { controls }
            }
            .disabled(pinch != nil)
            Text("Zoom \(Double(effective.scale / fit.scale).formatted(.percent.precision(.fractionLength(0))))")
            if let selected {
                Text("Point \(Int(selected.x.rounded())), \(Int(selected.y.rounded()))")
            } else {
                Text("Tap the diagram to inspect a point.")
            }
        }
    }

    @ViewBuilder private var controls: some View {
        Button("Zoom Out") { zoom(by: 1 / 1.25) }
            .disabled(committed.scale <= limits.lowerBound)
        Button("Zoom In") { zoom(by: 1.25) }
            .disabled(committed.scale >= limits.upperBound)
        Button("Reset") { committed = fit; selected = nil }
        Button("Inspect Center") { selected = CGPoint(x: 160, y: 120) }
    }
}

Apple’s MagnifyGesture supplies the magnification and starting location. The gesture sits on the fixed-size viewport, outside the content transform, so its positions use the space our equation expects.

Every update is calculated from committed, the transform from before this gesture. The magnification is cumulative for the current pinch; repeatedly multiplying the already-updated scale by that cumulative value would compound it. onEnded commits once. Starting a second pinch with factor 1 produces the existing transform, even when its starting location differs.

The temporary value belongs to @GestureState. Apple’s updating contract resets it when the gesture ends or is cancelled. The buttons are disabled during a pinch so they cannot replace its baseline halfway through. Programmatic zoom and reset are deliberately immediate; we have not introduced an animation that needs a Reduce Motion exception.

The tap uses the inverse transform. A tap in the letterbox margin clears selection rather than inventing a point outside the drawing. “Inspect Center” provides an ordinary button for choosing the known reference point without a precision tap. These controls are alternatives to the zoom gesture, not a claim that a coordinate-based diagram is fully accessible to every assistive technology.

Decide what resizing means

A changed viewport needs a policy. This example starts a fresh inspection session when its dimensions or document ID change. Zoom and selection reset together. That is appropriate for this small inspector; a drawing editor might instead preserve the content point under the viewport center and keep annotations in a document model.

nonisolated struct InspectionIdentity: Hashable {
    let document: Int
    let width: CGFloat
    let height: CGFloat
}

struct DiagramDemo: View {
    @State private var document = 0

    var body: some View {
        VStack {
            Button("Switch Diagram") { document = document == 0 ? 1 : 0 }
            GeometryReader { geometry in
                let viewport = CGSize(width: geometry.size.width,
                                      height: max(0, geometry.size.height - 180))
                if viewport.width > 0, viewport.height > 0 {
                    DiagramInspector(viewport: viewport, alternate: document == 1)
                        .id(InspectionIdentity(document: document,
                                               width: viewport.width, height: viewport.height))
                }
            }
        }
        .padding()
    }
}

@main struct AnchoredZoomApp: App {
    var body: some Scene { WindowGroup { DiagramDemo() } }
}

The identity changes only when its inputs change. It is not a new random identifier on every redraw. Apple’s id(_:) contract resets the associated view state, including the committed transform and selected point. Keep the viewport calculation outside the transformed drawing; measuring its rendered bounds and feeding those back into layout creates a different problem.

The reserved area below the viewport gives the demonstration’s controls room to wrap. Adapt that layout to your product and Dynamic Type requirements. This is also a vector example: decoding a large photograph and managing its memory are separate responsibilities.

Test the second pinch

A useful test should be able to distinguish correct math from a convincing first animation:

  • Zoom at one point, then start another pinch at a different point. At factor 1, nothing should move.
  • Check the anchor equation before bounds correction, including requests beyond the minimum and maximum scale.
  • Check centering and edge clamping separately. Do not call their intentional anchor movement a failed invariant.
  • Tap a transformed point and compare the saved content coordinate. Tap a letterbox margin and ensure it is rejected.
  • Resize or replace the diagram during interaction, then verify the new session starts fitted and old work does not alter it.
  • Exercise the ordinary buttons and real two-finger input, not just a helper function called “pinch.”

The exact assembled app compiles for an iOS 17 deployment target with Xcode 27.0 and Swift 6.4, with warnings treated as errors, under both ordinary and MainActor default isolation. The domain checks exercise 180 independently calculated anchor/scale combinations plus bounds, inverse selection, invalid factors, and repeated-gesture cases.

Five native tests pass in each isolation mode on an iPhone 18 Pro running the iOS 27 Simulator. They exercise actual two-finger gestures and rendered marker positions, inverse taps and margin rejection, control limits, document replacement, and viewport changes including rotation. A timed replacement during a slow XCTest pinch command also leaves the new session fitted and usable; it does not prove that a recognizer was active at the exact replacement instant. Cancellation reset above is Apple’s documented contract, not a directly observed system-cancellation result. These checks do not establish physical-device, older-runtime, VoiceOver, or large-photo behavior.

A zoom feature gets easier to reason about once the drawing, touches, and stored points have explicit coordinate spaces. Keep that boundary stable, and the next gesture can continue the inspection instead of starting a small treasure hunt.