Pinch to zoom out using UIPinchGestureRecognizer

25 Views Asked by At

Strangely, my app's UIPinchGestureRecognizer is making it so that moving my fingers together zooms in, and moving my fingers apart zooms out -- which is the opposite of how iOS normally works.

I don't think it's relevant, but: I'm using this in a SpriteKit application.

What am I doing wrong? How do I make UIPinchGestureRecognizer enable the normal iOS pinch-out-to-zoom-in and pinch-in-to-zoom-out behavior?

let pinch = UIPinchGestureRecognizer(target: self, action: #selector(GameScene.pinchZoom))

self.thisView?.addGestureRecognizer(pinch)
var normalCameraScale: CGFloat?
var accumulatedCameraScale: CGFloat = 1.0
    
@objc func pinchZoom(_ gesture: UIPinchGestureRecognizer) {
    if self.normalCameraScale == nil {
        self.normalCameraScale = self.camera?.xScale ?? 1.0
        self.accumulatedCameraScale = self.normalCameraScale!
    }
    
    let maxScale: CGFloat = 10.0
        
    
    let newScale = gesture.scale * self.accumulatedCameraScale
        
    if newScale <= maxScale && newScale >= self.normalCameraScale! {
        self.camera?.setScale(newScale)
    }
        
    if gesture.state == .ended {
        self.accumulatedCameraScale = self.camera?.xScale ?? 1.0
    }
        
        
}

Thanks

1

There are 1 best solutions below

1
West1 On

As described here, this formula solves this problem:

self.accumulatedCameraScale * 1 / gesture.scale

The full function:

var normalCameraScale: CGFloat?
var accumulatedCameraScale: CGFloat = 1.0
    
@objc func pinchZoom(_ gesture: UIPinchGestureRecognizer) {
  if self.normalCameraScale == nil {
       self.normalCameraScale = self.camera?.xScale ?? 1.0
       self.accumulatedCameraScale = self.normalCameraScale!
  }
    
  let maxScale: CGFloat = 10.0
        
  //This formula makes it work correctly:
  let newScale = self.accumulatedCameraScale * 1 / gesture.scale
        
  if newScale <= maxScale && newScale >= self.normalCameraScale! {
     self.camera?.setScale(newScale)
  }
        
  if gesture.state == .ended {
     self.accumulatedCameraScale = self.camera?.xScale ?? 1.0
  }
        
}