如何根据 Swift 中的角度旋转图像?

How to rotate image based on angle in Swift?

我正在尝试旋转和成像,以便像指南针一样直观地向用户显示方向。因此,我试图将一个角度提供给函数以沿角度的方向旋转图像,但图像只是旋转失控并且在它最终停止时似乎不正确。每次委托触发时都会调用此函数:locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!)。有人能指出我正确的方向吗?

func headingDidChange(headingAngle: Double) {
    UIView.animateWithDuration(1.0, animations: {
        self.compassImage.transform = CGAffineTransformMakeRotation(CGFloat(headingAngle))
    })
}

尝试在委托方法中使用以下代码来旋转您的图像。

    let oldRad:Float = 1.259374
    let newRad:Float = 1.239832

    let theAnimation = CABasicAnimation(keyPath: "transform.rotation")

    theAnimation.fromValue = NSNumber(float: oldRad)
    theAnimation.toValue = NSNumber(float: newRad)

    theAnimation.duration = 0.2

    self.compassImage!.layer.addAnimation(theAnimation, forKey: "animateMyRotation")

    self.compassImage!.transform = CGAffineTransformMakeRotation(CGFloat(newRad))