计算旋转速度自然旋转视图iOS

Calculate rotation velocity and naturally rotate view iOS

我有一个圆形视图并通过以下代码覆盖 touchesBegan(touches:, withEvent:)touchesMoved(touches:, withEvent:).

使其旋转
var deltaAngle = CGFloat(0)
var startTransform: CGAffineTransform?

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    let touchPoint = touches.first!.locationInView(view)

    let dx = touchPoint.x - view.center.x
    let dy = touchPoint.y - view.center.y

    deltaAngle = atan2(dy, dx)
    startTransform = arrowPickerView.transform
}

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?)
{
    let touchPoint = touches.first!.locationInView(view)

    let dx = touchPoint.x - view.center.x
    let dy = touchPoint.y - view.center.y
    let angle = atan2(dy, dx)
    let angleDifference = deltaAngle - angle
    let transform = CGAffineTransformRotate(startTransform!, -angleDifference)
    arrowPickerView.transform = transform
}

我想覆盖 touchesEnded(touches:, withEvent:) 来计算速度并让视图自然旋转一点(类似于连续滚动)。我目前保存原始变换并计算增量角。我该如何实施?提前致谢!

在我下面的示例中,CGAffineTransformRotate 取决于:

  • 方向(如果用户从左向右、向上或向下等移动)
  • 旋转(取决于 touchesBegan 和 touchesEnded 之间的时间的因素)
  • PI

这将创建一个 CGAffineTransformRotate 并以持续时间 1 (s) 旋转,以创建动态滚动的感觉,使用 UIViewAnimationOptions.CurveEaseOut 属性

override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {

    let touchPointEnd = touches.first!.locationInView(view)

    self.dateTouchesEnded = NSDate()

    let delay : NSTimeInterval = NSTimeInterval(0)

    let timeDelta : Double = self.dateTouchesEnded!.timeIntervalSince1970 - self.dateTouchesStarted!.timeIntervalSince1970

    let horizontalDistance : Double = Double(touchPointEnd.x - self.touchPointStart!.x)
    let verticalDistance : Double = Double(touchPointEnd.y - self.touchPointStart!.y)

    var direction : Double = 1
    if (fabs(horizontalDistance) > fabs(verticalDistance)) {
        if horizontalDistance > 0 {
            direction = -1
        }
    } else {
        if verticalDistance < 0 {
            direction = -1
        }
    }

    let rotation : Double = (0.1 / timeDelta < 0.99) ? 0.1 / timeDelta : 0.99

    let duration : NSTimeInterval = NSTimeInterval(1)
    UIView.animateWithDuration(duration, delay: delay, options: UIViewAnimationOptions.CurveEaseOut, animations: {
        let transform = CGAffineTransformRotate(self.imageView.transform, CGFloat(direction) * CGFloat(rotation) * CGFloat(M_PI))
        self.imageView.transform = transform
        }, completion: nil)

}

我添加了变量来跟踪触摸的开始和结束时间,并添加了 touchesBegan 函数的 CGPoint 位置

var dateTouchesStarted : NSDate?
var dateTouchesEnded : NSDate?
var touchPointStart : CGPoint?

我在 touchesBegan 中添加了:

self.touchPointStart = touchPoint

如上所述设置变量。