Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iphone sdk CGAffineTransform getting the angle of rotation of an object

how do i calculate the angle of rotation for any given object (ie a uiimageview)?

like image 737
nathanjosiah Avatar asked Jan 12 '10 19:01

nathanjosiah


3 Answers

Technically you can't, because the transform can include a skew operation which turns the image into a parallelogram and the rotation angle isn't defined anymore.

Anyway, since the rotation matrix generates

 cos(x)  sin(x)   0
-sin(x)  cos(x)   0
   0        0     1

You can recover the angle with

return atan2(transform.b, transform.a);
like image 69
kennytm Avatar answered Oct 01 '22 15:10

kennytm


You can easily get the angle of the rotation like this:

CGFloat angle = [(NSNumber *)[view valueForKeyPath:@"layer.transform.rotation.z"] floatValue];

For example:

view.transform = CGAffineTransformMakeRotation(0.02);
CGFloat angle = [(NSNumber *)[view valueForKeyPath:@"layer.transform.rotation.z"] floatValue];
NSLog(@"%f", angle); // 0.020000

From the documentation:

Core Animation extends the key-value coding protocol to allow getting and setting of the common values of a layer's CATransform3D matrix through key paths. Table 4 describes the key paths for which a layer’s transform and sublayerTransform properties are key-value coding and observing compliant

like image 23
sch Avatar answered Oct 01 '22 13:10

sch


Or you can use acos and asin functions. You will get exactly the same result:

 NSLog (@"%f %f %f", acos (MyView.transform.a), asin (MyView.transform.b), atan2(MyView.transform.b, MyView.transform.a) );
like image 35
leon Avatar answered Oct 01 '22 15:10

leon