CGAffineTransform UIView with UIPanGestureRecognizer

CGAffineTransform an UIView with UIPanGestureRecognizer

我有视图 A,在自己的视图上添加子视图。我希望当我在视图 A 上绘制 panGestureRegonizer 时,视图 A 将跟随绘制移动。

并且在移动视图 A 时会缩放。当视图移动到屏幕的 top/left/bottom/right 时,视图 A 将缩放到较小,当视图移动到屏幕中心时,视图 A 将缩放到更大。

我尝试了很多解决方案,但我做不到。

请建议帮助我?

逻辑:你有以中心、x 和 y 为中心的坐标系 (CS)。当用户使用平移手势时,he/she 在 CS 中生成点序列。所以我们的任务是测量 CS 中心和用户点之间的距离。当距离最远时,我们可以计算缩放视图的比例因子。

var center: CGPoint! //center of the CS
let maxSize: CGSize = CGSize.init(width: 100, height: 100) // maximum size of our scaling view
var maxLengthToCenter: CGFloat! //maximum distance from the center of the CS to the furthest point in the CS

private func prepareForScaling() {
    self.center = self.view.center //we set the center of our CS to equal the center of the VC's view
    let frame = self.view.frame
    //the furthest distance in the CS is the diagonal, and we calculate it using pythagoras theorem
    self.maxLengthToCenter = (frame.width*frame.width + frame.height*frame.height).squareRoot() 
}

然后我们需要调用我们的设置函数让我们的数据准备好缩放功能 - 我们可以在 viewDidLoad 中执行此操作:

override func viewDidLoad() {
    super.viewDidLoad()  
    self.prepareForScaling()
}

然后我们需要一个辅助函数来计算我们视图的缩放大小,用于用户在屏幕上的平移手势当前位置。

private func scaledSize(for location: CGPoint) -> CGSize {
    //calculate location x,y differences from the center
    let xDifference = location.x - self.center.x
    let yDifference = location.y - self.center.y

    //calculate the scale factor - note that this factor will be between 0.0(center) and 0.5(diagonal - furthest point)    
    //It is due our measurement - from center to view's edge. Consider multiplying this factor with your custom constant.
    let scaleFactor = (xDifference*xDifference + yDifference*yDifference).squareRoot()/maxLengthToCenter
    //create scaled size with maxSize and current scale factor
    let scaledSize = CGSize.init(width: maxSize.width*(1-scaleFactor), height: maxSize.height*(1-scaleFactor))

    return scaledSize
}

最后,我们需要修改平移手势动作来改变 A 的大小:

@IBAction func panGestureAction(_ sender: UIPanGestureRecognizer) {
    UIView.animateKeyframes(withDuration: 0.1, delay: 0, options: UIViewKeyframeAnimationOptions.calculationModeLinear, animations: {

        let location = sender.location(in: sender.view?.superview)

        sender.view?.frame = CGRect.init(origin: CGPoint.init(x: 0, y: 0), size: self.scaledSize(for: location))

        sender.view?.center = location
    })
}