Search code examples
iphoneobjective-ccocoa-touchcalayer

Scale and move a layer simultaneously


I am using CABasicAnimation to change the bounds property and then using it to change the position property of a layer. Is it possibly to do both simultaneously? Kinda of like changing the frame of the UIView?

CGRect oldBounds = mask.bounds;
CGRect newBounds = CGRectMake(0,0, rect.size.width * scale, rect.size.height * scale);
NSLog(@"%@", NSStringFromCGRect(newBounds));
CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"bounds"];

animation.fromValue = [NSValue valueWithCGRect:oldBounds];
animation.toValue = [NSValue valueWithCGRect:newBounds];

mask.bounds = newBounds;
[mask addAnimation:animation forKey:@"bounds"];



CGPoint oldPos = mask.position;
CGPoint newPos = CGPointMake(rect.origin.x * scale, rect.origin.y * scale);

CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@"position"];

animation2.fromValue = [NSValue valueWithCGPoint:oldPos];
animation2.toValue = [NSValue valueWithCGPoint:newPos];

mask.position = newPos;
[mask addAnimation:animation2 forKey:@"position"];

Solution

  • EDIT: Changed to give more correct animations...

    You can add 2 animations at once...

    Like this:

    CALayer * myLayer ;
    
    {
        CABasicAnimation * anim = [ CABasicAnimation animationWithKeyPath:@"position" ] ;
        anim.fromValue = [ NSValue valueWithCGPoint:layer.position ] ;
        [ layer addAnimation:anim forKey:nil ] ;
    }
    
    layer.position = <#newPosition#> ;
    
    {
        CABasicAnimation * anim = [ CABasicAnimation animationWithKeyPath:@"bounds" ] ;
        anim.fromValue = [ NSValue valueWithCGRect:layer.bounds ] ;
        [ layer addAnimation:anim forKey:nil ] ;
    }
    
    layer.bounds = <#newBounds#> ;