将NSImageView的CALayer旋转90度

时间:2011-10-02 04:23:05

标签: macos cocoa core-animation

我正在尝试旋转NSImageView的CALayer。我的问题是anchorPoint默认显示为(0.0,0.0),但我希望它是图像的中心(Apple的文档表明默认值应该是中心(0.5,0.5),但它不在我的系统操作系统上X 10.7),当我修改锚点时,图像中心的原点移动到左下角。

以下是我用来旋转图层的代码:

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"];  

1 个答案:

答案 0 :(得分:4)

似乎改变某些东西的锚点也会改变它的位置。以下代码段修复了此问题:

  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;