Search code examples
ioscocoa-touchcore-animationcaanimation

Red Box Moving in Place of UIImage View in Core Animation


My first Core Animation is just an image moving from point a to b. For some reason when the animation is called a red box appears and moves in place of my image while it just sits there. Here is my code:

-(IBAction)preform:(id)sender{
CALayer *layer = [CALayer layer];
[layer setPosition:CGPointMake(100.0, 100.0)];
[layer setBounds:CGRectMake(0.0, 0.0, 50.0, 60.0)];
[layer setBackgroundColor:[[UIColor redColor] CGColor]];
[imView.layer addSublayer:layer];

CGPoint point = CGPointMake(imView.frame.origin.x, imView.frame.origin.y);
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.fromValue  = [NSValue valueWithCGPoint:point];
anim.toValue    = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
anim.duration   = 1.5f;
anim.repeatCount =1;
anim.removedOnCompletion = YES;
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
[layer  addAnimation:anim forKey:@"position"];
}

Solution

  • If you don't need that red box for your app's UI, don't create it and instead apply the animation to the view's layer. If you do need that red box, do create, but apply the animation to the view's layer, not the red box layer

    Also note that unless your change your layer's anchorPoint, the position property actually is the center of the layer, not the corner. You need to take that in account for making smooth animations.

    Finally, if you don't want your view to snap back after the animation is done, you will need to set it's new position. Don't worry, while the animation is in play, the view's relocation isn't visible.

    Suggested (and untested) code:

    -(IBAction)preform:(id)sender{
    
      CGPoint point = CGPointMake(imView.frame.size.width/2.0 , imView.frame.size.height/2.0 );
      CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
      anim.fromValue  = [NSValue valueWithCGPoint:point];
      anim.toValue    = [NSValue valueWithCGPoint:CGPointMake(point.x + 50, point.y)];
      anim.duration   = 1.5f;
      anim.repeatCount =1;
      anim.removedOnCompletion = YES;
      anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
      [imView.layer  addAnimation:anim forKey:@"position"];
    
      imView.center = CGPointMake( imView.center.x + 50, imView.center.y
    }
    

    This would all be easier if you used the UIView animation helper functions instead, but I figure you are trying to learn how to use CAAnimation