SwiftUI Gestures MagnificationGesture
SwiftUI Gestures: 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
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 } }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { MagnifyDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
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
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 } }
)
}
}
import SwiftUI
struct ContentView: View {
var body: some View { MagnifyClampedDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the zoom is clamped between 0.5x and 2x.