90 degree rotating CALayer NSImageView

I am trying to rotate CALayer from NSImageView. My problem is that the default anchor pointer is (0.0, 0.0), but I want it to be the center of the image (Apple's documentation indicates that the default value should be in the center (0.5, 0.5), but this is not on my operating system X 10.7). When I change the anchor point, the beginning of the center of the image is shifted to the lower left corner.

Here is the code I use to rotate the layer:

CALayer *myLayer = [imageView layer]; CGFloat myRotationAngle = -M_PI_2; NSNumber *rotationAtStart = [myLayer valueForKeyPath:@"transform.rotation"]; CATransform3D myRotationTransform = CATransform3DRotate(myLayer.transform, myRotationAngle, 0.0, 0.0, 1.0); myLayer.transform = myRotationTransform; CABasicAnimation *myAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; myAnimation.duration = 1.0; myAnimation.fromValue = rotationAtStart; myAnimation.toValue = [NSNumber numberWithFloat:([rotationAtStart floatValue] + myRotationAngle)]; [myLayer addAnimation:myAnimation forKey:@"transform.rotation"]; myLayer.anchorPoint = CGPointMake(0.5, 0.5); [myLayer addAnimation:myAnimation forKey:@"transform.rotation"]; 
+4
source share
1 answer

It seems that changing the anchor point also changes its position. The following snippet fixes the problem:

  CGPoint anchorPoint = CGPointMake(0.5, 0.5); CGPoint newPoint = CGPointMake(disclosureTriangle.bounds.size.width * anchorPoint.x, disclosureTriangle.bounds.size.height * anchorPoint.y); CGPoint oldPoint = CGPointMake(disclosureTriangle.bounds.size.width * disclosureTriangle.layer.anchorPoint.x, disclosureTriangle.bounds.size.height * disclosureTriangle.layer.anchorPoint.y); newPoint = CGPointApplyAffineTransform(newPoint, [disclosureTriangle.layer affineTransform]); oldPoint = CGPointApplyAffineTransform(oldPoint, [disclosureTriangle.layer affineTransform]); CGPoint position = disclosureTriangle.layer.position; position.x -= oldPoint.x; position.x += newPoint.x; position.y -= oldPoint.y; position.y += newPoint.y; disclosureTriangle.layer.position = position; disclosureTriangle.layer.anchorPoint = anchorPoint; 
+4
source