I want to allow the user to pinch-to-zoom in on an Image in SwiftUI. I figured the best way to go was to use a MagnificationGesture
and, following along with the answer here, I ended up with this code:
// outside of `var body: some View`
@State private var scale: Int = 1.0
@State private var lastScale: Int = 1.0
// Image
Image("dog")
.resizable()
.aspectRatio(contentMode: .fit)
.gesture(MagnificationGesture()
.onChanged { val in
let delta = val / self.lastScale
self.lastScale = val
let newScale = self.scale * delta
self.scale = newScale
}
.onEnded { _ in
self.lastScale = 1.0
}
)
.scaleEffect(scale)
This code handles magnification fine, but does not let the user zoom in on a specific area. Instead, it always zooms in on the middle of the image.
How would I go about handling pinch-to-zoom behavior on an image in SwiftUI?