0

I am rotating image through this code

UIView.animate(withDuration: 2) {

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

    }

Problem is that it is rotating in shortest path. I want always clockwise rotation and rotation degree is variable. this and this does not provide a solution.

Salman Khalid
  • 543
  • 5
  • 23

2 Answers2

2

Just split it to two animations if the angle is more than 180°.

1

You can rotate your Image as per your requirement with the help of CoreAnimation like below:

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()
}
iPeter
  • 1,330
  • 10
  • 26