How to zoom and pan image in ScrollView

93 views Asked by At

I'm dealing with zoom&pan topic in my SwiftUI app. I use following View struct to display image

struct PictureDetailView: View {

@State private var zoom: Double
private var image: NSImage
private var minZoom: Double

init(data: Data) {
    image = NSImage(data: data)!
    let zoom = 600 / Double(image.size.width)
    _zoom = State(initialValue: zoom)
    minZoom = zoom
}

var body: some View {
    VStack {
        ScrollView([.horizontal, .vertical]) {
            Image(nsImage: image).resizable().scaledToFit().border(.black, width: 2)
                .scaleEffect(zoom)
        }
        Slider(value: $zoom, in: minZoom...5)
    }.padding().frame(width: 600, height: 400)
}
}

Difficulty I face is that if the image is zoomed out it disappears from visible area of ScrollView and I'm wondering whether there is any easy way how to keep image always visible (the best will be centered in visible area of ScrollView) while it's zoomed in or out. Thanks.

1

There are 1 answers

0
tillus On

If you want to integrate a pan gesture, maybe it is better to integrate UIKit's UIScrollView through UIViewRepresentable instead of SwiftUI's ScrollView instead. This not only makes it a lot easier to center your image properly, but it also comes with an integrated pan gesture recognizer.

UIScrollView for SwiftUI