Determine how much a CALayer has rotated

2019-03-25 16:28发布

问题:

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?

回答1:

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