CGAffineTransformMakeRotation with negative M_PI

I am using CGAffineTransformMakeRotation to rotate a UIView inside an animation block, and I want to rotate it counterclockwise for 180ΒΊ .

However, when I put

 myView.animateWithDuration(0.5) myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI)) 

it still rotates clockwise. What confuses me is that if I write β€œmanually” the value of M_PI , it will work as expected

  // this will rotate counterclockwise myView.transform = CGAffineTransformMakeRotation(CGFloat(-3.14159265358979)) 

Why is this behavior?

Edit: Added I am using an animation block

+5
source share
2 answers

As I said in my first comment and as Segii already wrote: the animation will take the shortest distance between where this value is now and where it is trying. CABasicAnimation best solution is to use CABasicAnimation to force counterclockwise rotation:

 let anim = CABasicAnimation(keyPath: "transform.rotation") anim.fromValue = M_PI anim.toValue = 0 anim.additive = true anim.duration = 2.0 myView.layer.addAnimation(anim, forKey: "rotate") myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI)) 

This will rotate it 180 counterclockwise at a time.

The angle you specify in the last line + fromValue is the starting angle β†’ 0. And then the rotation will go a distance (toValue - fromValue) = 0 - M_PI = - M_PI β†’ 180 degrees counterclockwise.

+8
source

As I understand it, you are trying to rotate the view in the animation block. animateWithDuration will always perform the animation in the shortest animateWithDuration way. Thus, M_PI and -M_PI give the same destination position. The reason you get the expected direction of the animation when manually tuned is because your manual value is really less than the M_PI, so the shortest way is to turn it counterclockwise.

To get the expected behavior, you will need to combine at least two animations, dividing the rotation angle. for instance

 //first animation block myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI/2))CGAffineTransformMakeRotation; //second animation block myView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI/2))CGAffineTransformMakeRotation; 

Swift 3.0

 myView.transform = CGAffineTransform(rotationAngle: CGFloat(-M_PI/2)) 

Or, much more reliably, use CAKeyframeAnimation

+5
source

All Articles