ios UIImageView 旋转方向 swift 顺时针方向可变度数

ios UIImageView rotation direction in swift at variable degree in clockwise direction

我正在通过这段代码旋转图像

UIView.animate(withDuration: 2) {

        self.blueNeedleImageView.transform = CGAffineTransform(rotationAngle: CGFloat(myDegreeValue * Double.pi / 180))

    }

问题是它在最短路径上旋转。我想要总是顺时针旋转,旋转度数是可变的。 this and this 未提供解决方案。

如果角度大于180°就拆分成两个动画

您可以在 CoreAnimation 的帮助下根据您的要求旋转图像,如下所示:

let angle = myDegreeValue
if let n = NumberFormatter().number(from: angle) {
    let floatAngle = Double(truncating: n)
    CATransaction.begin()
    let rotationAnimation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotationAnimation.byValue = NSNumber(value: floatAngle * (Double.pi / 180))
    rotationAnimation.duration = 2
    rotationAnimation.isRemovedOnCompletion = true

    CATransaction.setCompletionBlock {
          self.blueNeedleImageView.transform = CGAffineTransform(rotationAngle: CGFloat(floatAngle * (Double.pi / 180)))
    }
    self.blueNeedleImageView.layer.add(rotationAnimation, forKey: "rotationAnimation")
    CATransaction.commit()
}