CALayer的frame屬性是派生屬性,取決於圖層的位置,anchorPoint,邊界和變換。取而代之的是對框架進行動畫處理,而不是對框架進行動畫處理,而應根據您要實現的效果來設置動畫位置或邊界。
要移動一個層,你可以動畫position
:
-(void)moveLayer:(CALayer*)layer to:(CGPoint)point
{
// Prepare the animation from the current position to the new position
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
animation.fromValue = [layer valueForKey:@"position"];
// NSValue/+valueWithPoint:(NSPoint)point is available on Mac OS X
// NSValue/+valueWithCGPoint:(CGPoint)point is available on iOS
// comment/uncomment the corresponding lines depending on which platform you're targeting
// Mac OS X
animation.toValue = [NSValue valueWithPoint:NSPointFromCGPoint(point)];
// iOS
//animation.toValue = [NSValue valueWithCGPoint:point];
// Update the layer's position so that the layer doesn't snap back when the animation completes.
layer.position = point;
// Add the animation, overriding the implicit animation.
[layer addAnimation:animation forKey:@"position"];
}
要調整層,你會動畫bounds
參數:
-(void)resizeLayer:(CALayer*)layer to:(CGSize)size
{
// Prepare the animation from the old size to the new size
CGRect oldBounds = layer.bounds;
CGRect newBounds = oldBounds;
newBounds.size = size;
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];
// NSValue/+valueWithRect:(NSRect)rect is available on Mac OS X
// NSValue/+valueWithCGRect:(CGRect)rect is available on iOS
// comment/uncomment the corresponding lines depending on which platform you're targeting
// Mac OS X
animation.fromValue = [NSValue valueWithRect:NSRectFromCGRect(oldBounds)];
animation.toValue = [NSValue valueWithRect:NSRectFromCGRect(newBounds)];
// iOS
//animation.fromValue = [NSValue valueWithCGRect:oldBounds];
//animation.toValue = [NSValue valueWithCGRect:newBounds];
// Update the layer's bounds so the layer doesn't snap back when the animation completes.
layer.bounds = newBounds;
// Add the animation, overriding the implicit animation.
[layer addAnimation:animation forKey:@"bounds"];
}
您可以使用CAAnimationGroup如果結合這些動畫您需要同時移動和調整圖層大小。
謝謝弗拉基米爾。我發現CALayer不能直接爲框架屬性設置動畫。文檔說明在灰色框中。由於某種原因沒有看到它。 – dontWatchMyProfile 2010-05-23 19:18:31
最後一行沒問題 - 你在addAnimation中指定的鍵值可以是任意的NSString。我認爲實際的答案是鈹的低於 – Mattia 2012-01-24 20:52:56
'[myLayer addAnimation:frameAnimation forKey:@「frame」];''frame'只是一個動畫的名稱,並且與實際的動畫無關...... – 2015-11-16 09:53:23