I am trying to rotate the CALayer of an NSImageView. My problem is that the anchorPoint appears to be (0.0, 0.0) by default but I want it to be the center of the image (Apple's documentation indicates the default should be the center (0.5, 0.5), but it's not on my system OS X 10.7), When I modify the anchor point the origin of the center of the image shifts to the lower left corner.
Here's the code I am using 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"];
It appears that changing the anchor point of something also changes it's 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;
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