Home > Blockchain >  Prevent MagnificationGesture zooming below original size of image
Prevent MagnificationGesture zooming below original size of image

Time:01-16

My current implementation of MagnificationGesture is allowing an image to be pinched and zoomed out to a very small size. I want to only allow the image to be zoomed in so have tried implementing a minZoom variable to try and control if the gesture should allow the user to zoom out. The image should never be allowed to zoom out further than its original size.

I've started with this code, but it's not working correctly, can anyone please help with a solution?

let minZoom: CGFloat = 1

var images: [Space.SpaceImage]

@GestureState var scale: CGFloat = 1
@State private var imageScale: CGFloat = 1.0

var magnification: some Gesture {
    MagnificationGesture()
        .updating($scale) { currentState, gestureState, _ in
            gestureState = currentState
            if currentState >= minZoom {
                imageScale = scale
            }
        }
}

CodePudding user response:

You can use the max function when setting the scaleEffect to make sure it is never less than minZoom, as follows:

struct ContentView: View {
    
    let minZoom: CGFloat = 1
    @State var scale: CGFloat = 1
    
    var body: some View {
        ZStack {
            Color.yellow
                .edgesIgnoringSafeArea(.all)
            Image(systemName: "questionmark")
                .resizable()
                .frame(width: 100, height: 100)
                .scaleEffect(x: max(scale, minZoom), y: max(scale, minZoom))
                .gesture(magnification)
        }
    }
    
    var magnification: some Gesture {
        MagnificationGesture()
            .onChanged { scale in
                self.scale = scale
            }
    }
}

enter image description here

  • Related