How to apply pinch to zoom to an image in SwiftUI — iOS
2 min readMar 26, 2024
Using MagnificationGesture
, we can apply pinch to zoom to an image in SwiftUI. Here is an example:
import SwiftUI
struct ContentView: View {
@State private var currentZoom = 0.0
@State private var totalZoom = 1.0
var body: some View {
Image("image")
.resizable()
.scaledToFit()
.font(.title)
.scaleEffect(currentZoom + totalZoom)
.gesture(
MagnificationGesture()
.onChanged { value in
currentZoom = value - 1
}
.onEnded { value in
totalZoom += currentZoom
currentZoom = 0
}
)
}
}
#Preview(){
ContentView()
}
You can pinch in or pinch out in simulator by holding Option key + holding mouse
& then move.
Output:
In SwiftUI, we can use MagnificationGesture
to detect pinch gestures. Here:
- The
.onChanged
modifier adjusts the scale factor based on the pinch gesture's delta value. - The
scaleEffect
modifier is applied to the image to scale it based on thescale
state variable.
If you want to limit the scale factor to a range, we can write the code like this:
import SwiftUI
struct ContentView: View {
@State private var currentZoom = 0.0
@State private var totalZoom = 1.0
var body: some View {
Image("image")
.resizable()
.scaledToFit()
.font(.title)
.scaleEffect(currentZoom + totalZoom)
.gesture(
MagnificationGesture()
.onChanged { value in
currentZoom = min(max( value.magnitude, 0.2), 5.0) - 1
}
.onEnded { value in
totalZoom += currentZoom
currentZoom = 0
}
)
}
}
#Preview(){
ContentView()
}
Let’s connect in LinkedIn and explore new opportunities together!