0

I'm using CGAffineTransformMakeRotation to rotate a subview using its transform property. Later, I need to find out how far the subview has been rotated. I realize that I could simply use an int to keep track of this, but is there a simple way to get the current rotation of the subview?

The Kraken
  • 3,158
  • 5
  • 30
  • 67
  • Duplicate question found at:http://stackoverflow.com/questions/2051811/iphone-sdk-cgaffinetransform-getting-the-angle-of-rotation-of-an-object – The Kraken Apr 20 '12 at 23:13
  • 1
    Have a look at my [answer](http://stackoverflow.com/a/9712584/1207152) to the [question](http://stackoverflow.com/q/2051811/1207152) mentioned by @TheKraken. – sch Apr 20 '12 at 23:21

1 Answers1

5

CGAffineTransformMakeRotation is explicitly defined to return a matrix with cos(angle) in the transform's a value, sin(angle) in b, etc (and, given the way the transform works, that's the only thing it really could do).

Hence you can work out the current rotation by doing some simple inverse trigonometry. atan2 is probably the thing to use, because it'll automatically figure out the quadrants appropriately.

So, e.g.

- (float)currentAngleOfView:(UIView *)view
{
    CGAffineTransform transform = view.transform;
    return atan2f(transform.b, transform.a);
}

Because that'll do an arctangent that'll involve dividing the a and b fields in an appropriate manner, that method will continue to work even if you apply scaling (as long as it's the same to each axis) or translation.

If you want to apply more complex or arbitrary transformations then things get a lot more complicated. You'll want to look how to calculate normal matrices. From memory I think you'd want the adjugate, which is about as much fun to work out as it sounds.

Tommy
  • 99,986
  • 12
  • 185
  • 204