項目中要求子菜單的彈出動畫為圍繞點擊的靠近點展開放大,而不是從中心展開,下面是動畫效果:
彈出動畫效果如圖.gif
在iOS中,anchorPoint點的值是用一種相對bounds的比例值來確定的,在白紙的左上角、右下角,anchorPoint分為為(0,0), (1, 1)。類似地,可以得出在白紙的中心點、左下角和右上角的anchorPoint為(0.5,0.5), (0,1), (1,0)。
在實際情況中,可能還有這樣一種需求,我需要修改anchorPoint而不想移動layer,在修改anchorPoint后再重新設置一遍frame就可以達到目的,這時position就會自動進行相應的改變。
代碼:
- (void) setAnchorPoint:(CGPoint)anchorpoint forView:(UIView *)view{
CGRect oldFrame = view.frame;
view.layer.anchorPoint = anchorpoint;
view.frame = oldFrame;
}
我的彈出動畫效果實現代碼如下:
- (void)changeScaleAnimationToView:(UIView *)view {
view.alpha = 0;
CABasicAnimation *animationScale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
animationScale.duration = 0.2;
animationScale.repeatCount = 1;
animationScale.autoreverses = NO;
animationScale.fromValue = [NSNumber numberWithFloat:0.0]; // 開始時的倍率
animationScale.toValue = [NSNumber numberWithFloat:1.0]; // 結束時的倍率
animationScale.removedOnCompletion = YES;
CGRect frame = view.frame;
view.layer.anchorPoint = CGPointMake(1.0, 0.3);
view.frame = frame;
view.alpha = 1.0;
[view.layer addAnimation:animationScale forKey:@"scale-layer"];
}
關于anchorPoint的詳細解釋請參考如下鏈接。
參考鏈接:
徹底理解position與anchorPoint