Właściwość frame obiektu CALayer jest właściwością pochodną, zależną od położenia, anchorPoint, granic i transformacji warstwy. Zamiast animować klatkę, należy zamiast tego animować położenie lub granice, w zależności od tego, jaki efekt chcesz osiągnąć.
Aby przenieść warstwę można animować 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"];
}
Aby zmienić warstwę, byś animować parametr 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"];
}
Można łączyć te animacje za pomocą CAAnimationGroup if musisz przesuwać i zmieniać rozmiar warstwy w tym samym czasie.
Dzięki Vladimir. Odkryłem, że CALayer nie może bezpośrednio animować właściwości ramki. Dokumentacja mówi, że w szarym polu. Nie widziałem tego z jakiegoś powodu. – dontWatchMyProfile
Ostatnia linia jest w porządku, ponieważ jest - kluczem określonym w addAnimation może być arbitralny NSString. Myślę, że właściwą odpowiedzią jest beryl poniżej – Mattia
'[myLayer addAnimation: frameAnimation forKey: @" frame "];' 'frame' jest po prostu nazwą dla animacji i nie ma nic wspólnego z faktyczną animowaną właściwością ... –