11

How do I calculate the Rotation in Radians around Z-axis by giving a CATransform3D struct as the input?

basically what I need is the other way round of CATransform3DMakeRotation.

sch
  • 27,436
  • 3
  • 68
  • 83
ravinsp
  • 4,150
  • 2
  • 32
  • 43

2 Answers2

27

It depends on what axis you are doing the rotation on.

Rotation about the z-axis is represented as:

a  = angle in radians
x' = x*cos.a - y*sin.a
y' = x*sin.a + y*cos.a
z' = z

( cos.a  sin.a  0  0)
(-sin.a  cos.a  0  0)
( 0        0    1  0)
( 0        0    0  1)

so angle should be a = atan2(transform.m12, transform.m11);

Rotation about x-axis:

a  = angle in radians
y' = y*cos.a - z*sin.a
z' = y*sin.a + z*cos.a
x' = x

(1    0      0    0)
(0  cos.a  sin.a  0)
(0 -sin.a  cos.a  0)
(0    0     0     1)

Rotation about y-axis:

a  = angle in radians
z' = z*cos.a - x*sin.a
x' = z*sin.a + x*cos.a
y' = y

(cos.a  0  -sin.a   0)
(0      1    0      0)
(sin.a  0  cos.a    0)
(0      0    0      1) 
Nader Eloshaiker
  • 587
  • 5
  • 18
  • 1
    Be sure to use atan2 and not atan as the later will not give an angle in the correct quadrant. – Nader Eloshaiker Oct 15 '10 at 13:02
  • Thank you Nader, before your answer, I had resorted back to using CALayer's affineTransform property convert the Transform3D into an AffineTransform and then get the angle out of it from this calculation:http://stackoverflow.com/questions/2051811/iphone-sdk-cgaffinetransform-getting-the-angle-of-rotation-of-an-object Now I know, how to calculate directly from Transform3D. Thanks! – ravinsp Oct 16 '10 at 06:18
  • Yeah I learned about this back in first year uni and can remember asking my friend "why the he'll do we need to know this" – Nader Eloshaiker Oct 16 '10 at 12:51
  • You can calculate the angle from an affine transform too using atan2(transform.b, transform.a), the maths still holds true for a z-axis rotation – Nader Eloshaiker Oct 16 '10 at 13:00
17

If the transform is attached to a layer, then you can get the value of the rotation like follows:

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

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

efimovdk
  • 368
  • 4
  • 16
sch
  • 27,436
  • 3
  • 68
  • 83