Thuộc tính khung của một CALayer là thuộc tính bắt nguồn, phụ thuộc vào vị trí, anchorPoint, giới hạn và biến đổi của lớp. Thay vì làm động khung hình, bạn nên thay thế animate vị trí hoặc giới hạn, tùy thuộc vào hiệu ứng bạn đang cố gắng thực hiện.
Để di chuyển một lớp, bạn có thể animate 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"];
}
Để thay đổi kích thước một lớp, bạn sẽ animate bounds
tham số:
-(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"];
}
Bạn có thể kết hợp các hình ảnh động sử dụng một CAAnimationGroup nếu bạn cần phải di chuyển và thay đổi kích thước một lớp cùng một lúc.
Cảm ơn Vladimir. Tôi đã thấy rằng CALayer không thể sinh động trực tiếp thuộc tính khung. Tài liệu nói rằng trong một hộp màu xám. Đã không nhìn thấy nó vì một lý do nào đó. – dontWatchMyProfile
Dòng cuối cùng là tốt vì nó là - chìa khóa bạn chỉ định trong addAnimation có thể là một NSString tùy ý. Tôi nghĩ câu trả lời thực sự là beryllium bên dưới – Mattia
'[myLayer addAnimation: frameAnimation forKey: @" frame "];' 'frame' chỉ là tên cho hoạt hình và không có gì để làm với thuộc tính thực tế đang hoạt hình ... –