【问题标题】:Issue with scaling when UIView is rotated upside downUIView 倒置旋转时的缩放问题
【发布时间】:2022-11-10 09:03:28
【问题描述】:

我正在尝试使用UIPanGestureRecognizer 用一根手指旋转和缩放UIView,其中UIImageView 内部为subView。旋转和缩放在常规情况下都可以正常工作,但是当视图倒置旋转时,它会以相反的方向工作而不是按比例放大,反之亦然,当在角点旋转时,它也会闪烁,不能正常工作。结果显示在这些 GIF 中:

issue

another issue

这是我试图实现这一目标的方法:

   @objc func ScaleGest(gesture: UIPanGestureRecognizer) {
    guard let gestureSuperView = gesture.view?.superview else { return }

    let center = frameScaleBut.center
    let touchLocation = gesture.location(in: self.view)
    
    if gesture.state == UIPanGestureRecognizer.State.began {
        self.initialDistance = distance(center, touchLocation)
    } else if gesture.state == UIPanGestureRecognizer.State.changed {
        
        let dist = distance(center, touchLocation) - initialDistance
        
        let smallScale: CGFloat = editingMode == .sticker ? 90 : 190

        let nextScale: CGSize = CGSize(width: gestureSuperView.bounds.width + dist, height: gestureSuperView.bounds.height + dist)
        
        if (nextScale.width >= (self.view.frame.width * 0.8)) || nextScale.width <= smallScale {
            return
        }
        
        gestureSuperView.bounds.size = CGSize(width: gestureSuperView.bounds.width + dist, height: gestureSuperView.bounds.height + dist)
    }
   }

我从这个答案https://stackoverflow.com/a/1906659/20306199中得到了这个方法的距离

func distance(_ a: CGPoint, _ b: CGPoint) -> CGFloat {
    let xDist = a.x - b.x
    let yDist = a.y - b.y
    return CGFloat(sqrt(xDist * xDist + yDist * yDist))
}

当对象没有旋转时,这可以正常工作,但是我认为当对象倒置旋转时,它仍然可以使用相同的坐标,但实际上它应该以相反的方式使用这些值,任何人都可以帮助我理解或实现这一点,谢谢。

【问题讨论】:

  • 你能分享一下你是如何布局视图的吗?

标签: ios swift uiview uikit uipangesturerecognizer


【解决方案1】:

问题不在于distance(_:_:) 函数,而在于center 参数。您的center 参数是在小图像坐标空间中确定的,但gestureLocation 是在视图的坐标空间中确定的。您可以使用convert(_:to:) 方法来做到这一点。你可以阅读它here

升级版: 实际上你不需要计算frameScaleBut.centergesture.location(in: self.view) 之间的距离。为什么?因为self.initialDistance 几乎总是在 0 左右。所以let dist = distance(center, touchLocation) - initialDistance 总是正数。而是计算gestureSuperView.centergesture.location(in: self.view) 之间的距离。 gestureSuperView 已经在 view 坐标空间中。

【讨论】:

  • 我现在无法访问代码库,从现在开始是排灯节假期,所以我会在回到工作岗位后尽快尝试并通知你,谢谢。
  • 添加let center = superView.convert(frameScaleBut.center, to: self.view) 后,它解决了问题,并且在相反方向缩放工作正常,但是现在当我尝试缩小它时,它会增加大小,即使它旋转与否也是如此。
  • 你能帮帮我吗
  • 当然,让我考虑一下
  • 已更新,请查看
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-20
  • 1970-01-01
  • 2011-03-27
  • 1970-01-01
  • 2011-07-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多