La propriété frame d'une CALayer est une propriété dérivée, dépendant de la position, du point d'ancrage, des limites et de la transformation de la couche. Au lieu d'animer le cadre, vous devriez plutôt animer la position ou les limites, selon l'effet que vous essayez d'accomplir.
Pour déplacer une couche, vous pouvez animer le 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"];
}
Pour redimensionner une couche, vous animerait le paramètre 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"];
}
Vous pouvez combiner ces animations en utilisant un CAAnimationGroup si vous devez déplacer et redimensionner une couche en même temps.
Merci Vladimir. J'ai trouvé que CALayer ne peut pas animer la propriété frame directement. La documentation dit que dans une boîte grise. Je ne l'ai pas vu pour une raison quelconque. – dontWatchMyProfile
La dernière ligne est correcte telle qu'elle est - la clé que vous spécifiez dans addAnimation peut être un NSString arbitraire. Je pense que la réponse réelle est le béryllium ci-dessous – Mattia
'[myLayer addAnimation: frameAnimation forKey: @" frame "];' 'frame' est juste un nom pour l'animation et n'a rien à voir avec la propriété en cours d'animation ... –