2012-03-10 61 views
10

我想旋轉一個圖層的左上角,而不是中心。根據文檔,我將anchorPoint屬性設置爲[0,1]。該視圖在我的示例中旋轉了50°,但在開始動畫之前,視圖跳轉到屏幕上的另一個點。如何在特定的錨點處旋轉圖層而不跳過?

self.shakeTag.layer.anchorPoint = CGPointMake(0.0f, 1.0f); 
[UIView beginAnimations:@"rotate" context:nil]; 
[self.shakeTag.layer setTransform: 
    CATransform3DRotate(CATransform3DIdentity, 
    radians(50.0), 0.0f, 0.0f, 1.0f)]; 
[UIView commitAnimations]; 

radians()的定義如下:

static inline double radians (double degrees) {return degrees * M_PI/180;} 

當我使用的形象是4倍大,並有很多透明像素的,我可以在默認的錨定點[0.5將其旋轉,0.5],但我不想浪費無形像素的空間。任何想法如何防止旋轉之前的圖層跳躍?

+0

如果你認爲答案是正確的,這將是真棒,如果你接受。 – Krumelur 2013-08-08 10:32:41

+0

你需要在這裏看到我的答案:http://stackoverflow.com/a/22188420/550393 – 2cupsOfTech 2014-03-28 03:01:16

回答

20

更改錨點會影響視圖的位置。如果您更改定位點並且想要將視圖保留在當前位置,則需要更改視圖的位置。使用這樣的事情(從這裏取:Layer Position jumps at start of (Core) Animation)設置你的定位點,並賠償位置的變化:

-(void)setAnchorPoint:(CGPoint)anchorPoint forView:(UIView *)view 
{ 
    CGPoint newPoint = CGPointMake(view.bounds.size.width * anchorPoint.x, view.bounds.size.height * anchorPoint.y); 
    CGPoint oldPoint = CGPointMake(view.bounds.size.width * view.layer.anchorPoint.x, view.bounds.size.height * view.layer.anchorPoint.y); 

    newPoint = CGPointApplyAffineTransform(newPoint, view.transform); 
    oldPoint = CGPointApplyAffineTransform(oldPoint, view.transform); 

    CGPoint position = view.layer.position; 

    position.x -= oldPoint.x; 
    position.x += newPoint.x; 

    position.y -= oldPoint.y; 
    position.y += newPoint.y; 

    view.layer.position = position; 
    view.layer.anchorPoint = anchorPoint; 
} 

而且在這裏看到更多的細節:Changing my CALayer's anchorPoint moves the view