Reputation: 475
How would I be able to limit the scale of the UIPinchGestureRecognizer to a min and max level? (not using UIScrollView) I would like to set max size as image width and hight.
var pichCenter : CGPoint!
var touchPoint1 : CGPoint!
var touchPoint2 : CGPoint!
let maxScale : CGFloat = 1
var pinchStartImageCenter : CGPoint!
@objc func pinchAction(gesture: UIPinchGestureRecognizer) {
if gesture.state == UIGestureRecognizerState.began {
pinchStartImageCenter = imageView.center
touchPoint1 = gesture.location(ofTouch: 0, in: self.view)
touchPoint2 = gesture.location(ofTouch: 1, in: self.view)
pichCenter = CGPoint(x: (touchPoint1.x + touchPoint2.x) / 2, y: (touchPoint1.y + touchPoint2.y) / 2)
} else if gesture.state == UIGestureRecognizerState.changed {
var pinchScale : CGFloat
if gesture.scale > 1 {
pinchScale = 1 + gesture.scale/100
}else{
pinchScale = gesture.scale
}
if pinchScale*self.imageView.frame.width < editPhotoView.frame.width {
pinchScale = editPhotoView.frame.width/self.imageView.frame.width
}
scaleZoomedInOut *= pinchScale
let newCenter = CGPoint(x: pinchStartImageCenter.x - ((pichCenter.x - pinchStartImageCenter.x) * pinchScale - (pichCenter.x - pinchStartImageCenter.x)),y: pinchStartImageCenter.y - ((pichCenter.y - pinchStartImageCenter.y) * pinchScale - (pichCenter.y - pinchStartImageCenter.y)))
self.imageView.frame.size = CGSize(width: pinchScale*self.imageView.frame.width, height: pinchScale*self.imageView.frame.height)
imageView.center = newCenter
}
}
Upvotes: 3
Views: 2171
Reputation: 11242
If you have the maximum size with you, then it's just a matter comparing it with the max size and setting the new size.
Before setting the new frame, check if the value exceeds the maximum value or is less than the minimum value. If so, don't change the frame.
let newWidth = pinchScale * self.imageView.frame.width
let newHeight = pinchScale * self.imageView.frame.height
// You need to have the maximum and minimum values for comparison already stored
if (newWidth >= minimumWidth && newWidth <= maximumHeight) && (newHeight >= minimumHeight && newHeight <= maximumHeight) {
imageView.frame.size = CGSize(width: newWidth, height: newHeight)
}
Note: You might want to apply the same logic to other things that change during the pinch also like the center.
Upvotes: 3