2011-10-02 245 views
4

我想旋轉NSImageView的CALayer。我的問題是,默認情況下,anchorPoint看起來像是(0.0,0.0),但我希望它是圖像的中心(Apple的文檔指出默認應該是中心(0.5,0.5),但它不在我的系統操作系統上X 10.7),當我修改定位點時,圖像中心的原點移動到左下角。旋轉NSImageView的CALayer 90度

下面是我使用的旋轉層的代碼:

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

看來,如果我的anchorPoint代碼移動到awakeFromNib則起源似乎並沒有改變......我覺得有些事我要和方面缺少我的理解CoreAnimation – Cayden

+0

你的代碼清單是不完整的(尤其是因爲你提到的東西移動到-awakeFromNib)。請張貼所有相關的代碼,包括所有這些被調用的地方。還要解釋如何創建託管此圖層樹的視圖(從nib,從-initWithFrame,如何創建)。 –

回答

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;