开发者

iphone sdk CGAffineTransform getting the angle of rotation of an object

开发者 https://www.devze.com 2022-12-16 08:10 出处:网络
how do i 开发者_如何学编程calculate the angle of rotation for any given object (ie a uiimageview)?Technically you can\'t, because the transform can include a skew operation which turns the image into

how do i 开发者_如何学编程calculate the angle of rotation for any given object (ie a uiimageview)?


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);


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


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) );


You can try with this:

- (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);    
}


I know this is very old question but, if anyone like me faces with this problem using CALayers and CATransform3D, you can get angle 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

精彩评论

暂无评论...
验证码 换一张
取 消