Search code examples
iosswiftrotationuianimation

Rotate image more than 180 degrees


I'm using CGAffineTransformMakeRotation to transform and rotate an arrow in a meter.

Picture of arrow that animates inside gage

The problem I am facing is that when I rotate more then 180 degrees the arrow rotates counter clockwise.

My goal is to rotate the arrow clockwise in the range of 1 to 280 degrees.

Example of the function that rotates the arrow:

func rotateNeedel(value: Int){
    var value = 220 //for testing purpose
    let degrees:CGFloat = CGFloat(value)
    UIView.animateWithDuration(2.0, animations: {
        self.ImgMaalerArrow.transform = CGAffineTransformMakeRotation((degrees * CGFloat(M_PI)) / 180.0)
    })}

Solution

  • You can use CABasicAnimation to rotate the view Clock-Wise

    func rotateNeedel(value: Double, duration: Double){
    
        let fullRotation = CABasicAnimation(keyPath: "transform.rotation")
        fullRotation.fromValue = Double(0)
        fullRotation.toValue = Double((value * M_PI)/180)
        fullRotation.fillMode = kCAFillModeForwards
        fullRotation.duration = duration
        fullRotation.removedOnCompletion = false
    
        // add animation to your view
        self.ImgMaalerArrow.layer.addAnimation(fullRotation, forKey: "rotateViewAnimation")
    }