ios - 如何在 UIPinchGestureRecognizer 中限制缩放缩放的最大/最小比例
问题描述
我如何能够将 UIPinchGestureRecognizer 的规模限制在最小和最大级别?(不使用 UIScrollView)我想将最大尺寸设置为图像宽度和高度。
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
}
}
解决方案
如果您有最大尺寸,那么只需将其与最大尺寸进行比较并设置新尺寸即可。
在设置新帧之前,请检查该值是否超过最大值或小于最小值。如果是这样,请不要更改框架。
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)
}
注意:您可能希望将相同的逻辑应用于在捏合期间发生变化的其他事物,例如中心。
推荐阅读
- java - 限制在 firebase 实时数据库中添加的子项数量
- java - 如何在android studio中的背景图像上显示gif
- angular - 以 Angular 形式提交
- javascript - 与多个 index.html 反应
- java - 装饰器模式可以用行为模式代替来解决问题吗?
- mongodb - 无法在项目上执行目标 io.swagger:swagger-codegen-maven-plugin:2.2.3:generate (default) 代码生成失败
- ios - 通知未收到 iOS
- firebase - 添加 Firebase 存储包后 Unity android 无法构建
- asp.net-mvc - asp.net mvc 应用程序中 bin\roslyn\csc.exe 中的 exe 文件不允许在托管服务器中使用。如何解决这个问题?
- reactjs - 如何在令牌过期时创建注销