SwiftUI Gestures MagnificationGesture

MagnificationGesture

Pinch to zoom content using MagnificationGesture, often combined with .scaleEffect.


Syntax

Magnify: Use MagnificationGesture() to get a scale factor and apply it with .scaleEffect(scale).


Pinch to Zoom

Pinch the image to zoom in/out. Releasing snaps back to the original size.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct MagnifyDemo: View {
  @State private var scale: CGFloat = 1
  var body: some View {
Image(systemName: "photo")
  .resizable().scaledToFit().frame(height: 120)
  .scaleEffect(scale)
  .gesture(
    MagnificationGesture()
      .onChanged { value in scale = value }
      .onEnded { _ in withAnimation(.spring()) { scale = 1 } }
  )
} }

In the example above, pinching the image zooms in/out.

Releasing snaps back to the original size.


Clamp Scale Range

Limit the zoom between 0.5x and 2x to avoid miniaturization or excessive enlargement.

Example

Demo.swift

ContentView.swift

App.swift

import SwiftUI

struct MagnifyClampedDemo: View {
  @State private var scale: CGFloat = 1
  let minS: CGFloat = 0.5
  let maxS: CGFloat = 2.0
  func clamp(_ v: CGFloat) -> CGFloat { min(max(v, minS), maxS) }
  var body: some View {
Image(systemName: "photo")
  .resizable().scaledToFit().frame(height: 120)
  .scaleEffect(scale)
  .gesture(
    MagnificationGesture()
      .onChanged { value in scale = clamp(value) }
      .onEnded { _ in withAnimation(.easeInOut) { scale = 1 } }
  )
} }

In the example above, the zoom is clamped between 0.5x and 2x.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *