Iphone sdk CGAffineTransform getting object rotation angle

how can i calculate the rotation angle for any given object (i.e. uiimageview)?

+32
ios cocoa-touch
Jan 12 '10 at 19:41
source share
5 answers

Technically, you cannot, because the transformation may include a skew operation, which turns the image into a parallelogram, and the rotation angle is no longer defined.

In any case, since the rotation matrix generates

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

You can restore the angle with

 return atan2(transform.b, transform.a); 
+90
Jan 12 '10 at 19:47
source share

You can easily get the rotation angle as follows:

 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, allowing you to get and set common CATransform3D level matrix values ​​through key paths. Table 4 describes the key paths for which the transform properties of the layers and the Transform sublayer are key encoding and compliance

+36
Mar 15 2018-12-12T00:
source share

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) ); 
+3
Jan 24 2018-11-11T00: 00Z
source share

You can try:

 - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { CGPoint newLocationPoint = [[touches anyObject] locationInView:self.superview]; int x = self.center.x; int y = self.center.y; float dx = newLocationPoint.x - x; float dy = newLocationPoint.y - y; double angle = atan2(-dx,dy); self.layer.position = self.center; self.layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1); NSLog(@"touchesMoved %f %f %d,%d %f,%f angle:%f",newLocationPoint.x,newLocationPoint.y,x,y,dx,dy,angle); } 
0
Nov 30 '12 at 6:28
source share

I know this is a very old question, but if someone like me encounters this problem using CALayers and CATransform3D, you can get angular with:

 extension CATransform3D { var xAxisAngle: CGFloat { get { return atan2(self.m23, self.m33) } } var yAxisAngle: CGFloat { get { return atan2(self.m31, self.m11) } } var zAxisAngle: CGFloat { get { return atan2(self.m12, self.m11) } } } 
0
Sep 02 '19 at 12:22
source share



All Articles