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?
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
Swift Version
let angle : CGFloat = atan2(layer.transform.m12, layer.transform.m11)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With