Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine how much a CALayer has rotated

I have a program in which a CALayer has to be rotated to certain value. How can I determine the current rotation of a CALayer? I have a UIRotationGestureRecognizer that rotates the layer:

- (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer == rotationGestureRecognizer) {
        NSLog(@"gestureRecRotation: %f", rotationGestureRecognizer.rotation);
        CATransform3D current = _baseLayer.transform;
        _baseLayer.transform = CATransform3DRotate(current, rotationGestureRecognizer.rotation * M_PI / 180, 0, 0, 1.0);
    }
}

I start with a layer that has to be rotated a certain amount to fit a puzzle. So how do I get the current rotation of the layer?

like image 524
KaasCoder Avatar asked Mar 14 '12 23:03

KaasCoder


2 Answers

You can do the math and get the angle like this:

CATransform3D transform = _baseLayer.transform;
CGFloat angle = atan2(transform.m12, transform.m11);

But it is easier to do as follows:

CGFloat angle = [(NSNumber *)[_baseLayer 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

like image 129
sch Avatar answered Oct 27 '22 03:10

sch


Swift Version

let angle : CGFloat = atan2(layer.transform.m12, layer.transform.m11)
like image 2
Pratik Sodha Avatar answered Oct 27 '22 03:10

Pratik Sodha