Search code examples
iosswiftanimationios8core-animation

How to rotate image based on angle in Swift?


I'm trying to rotate and image to visually show the direction to a user like a compass. So I'm trying to feed an angle to a function to rotate the image in the angle's direction, but the image just spins out of control and doesn't seem to be correct when it finally stops. This function is getting called every time the delegate fires: locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!). Can someone point me in the right direction?

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

Solution

  • Try the following code in the delegate method to rotate your image.

        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))