我正在堆栈溢出后This Answer之后使用CABasicAnimation使用Pan手势旋转视图。 我已经尝试过,但是没有找到减速旋转的确切方法。 fileprivate let rotationAnimation = CABasicAnimation()
func rotate(to: CGFloat, duration: Double = 0) {
rotateAnimation.fromValue = to
rotateAnimation.toValue = to
rotateAnimation.duration = duration
rotateAnimation.repeatCount = 0
rotateAnimation.isRemovedOnCompletion = false
rotateAnimation.fillMode = kCAFillModeForwards
rotateAnimation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
imageView.layer.add(rotateAnimation, forKey: "transform.rotation.z")
}
func angle(from location: CGPoint) -> CGFloat {
let deltaY = location.y - view.center.y
let deltaX = location.x - view.center.x
let angle = atan2(deltaY, deltaX) * 180 / .pi
return angle < 0 ? abs(angle) : 360 - angle
}
extension FloatingPoint {
var degreesToRadians: Self { return self * .pi / 180 }
var radiansToDegrees: Self { return self * 180 / .pi }
}
extension UserDefaults {
/// rotation persistant computed property
var rotation: CGFloat {
get {
return CGFloat(double(forKey: "rotation"))
}
set {
set(Double(newValue), forKey: "rotation")
}
}
}
@objc func pan(_ gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: view)
let gestureRotation = CGFloat(angle(from: location)) - startRotationAngle
switch gesture.state {
case .began:
// set the start angle of rotation
startRotationAngle = angle(from: location)
case .changed:
rotate(to: rotation - gestureRotation.degreesToRadians)
case .ended:
// update the amount of rotation
rotation -= gestureRotation.degreesToRadians
default :
break
}
// save the final position of the rotation to defaults
UserDefaults.standard.rotation = rotation
}