12

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?

desertnaut
  • 57,590
  • 26
  • 140
  • 166
ntrupin
  • 454
  • 8
  • 13
  • Does this answer your question? [Isn't there an easy way to pinch to zoom in an image in Swiftui?](https://stackoverflow.com/questions/58341820/isnt-there-an-easy-way-to-pinch-to-zoom-in-an-image-in-swiftui) – kelalaka Sep 30 '22 at 18:56

1 Answers1

2

I found that the easiest way to achieve is to use PDFKit provided by Apple .

1.Start by creating PDFView

    import SwiftUI
    import PDFKit

    struct PhotoDetailView: UIViewRepresentable {
    let image: UIImage
    func makeUIView(context: Context) -> PDFView {
        let view = PDFView()
        view.document = PDFDocument()
        guard let page = PDFPage(image: image) else { return view }
        view.document?.insert(page, at: 0)
        view.autoScales = true
        view.backgroundColor = .clear
        return view
    }
    
    func updateUIView(_ uiView: PDFView, context: Context) {
        
    }
    }

2.Use in swiftUI view, like this

TabView(selection: $index,
                content:  {
                //this line
                PhotoDetailView(image: images[index])
                    .offset(imageViewerOffset)
                
        })
        .tabViewStyle(PageTabViewStyle(indexDisplayMode: .always))
Haolong
  • 31
  • 5