Search code examples
core-animationquartz-graphicscabasicanimation

Why does CABasicAnimation show two points moving?


I am trying to show a simple point moving. I set up a layer, set the bounds, position and color, and then use CAAnimation to show it moving

    CALayer *l = [CALayer layer];

    l.bounds = CGRectMake(0,0,20,20);
    l.position = CGPointMake(x,y);
    l.cornerRadius = 10;
    l.backgroundColor = [UIColor blueColor].CGColor;

    [self.theView.layer addSublayer:l];


    CABasicAnimation *anim1 = [CABasicAnimation animationWithKeyPath:@"position"];
    anim1.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
    CGPoint to = CGPointMake(x+dx, y+dy);
    anim1.fromValue = [l valueForKey:@"position"];
    anim1.toValue = [NSValue valueWithCGPoint:to];
    l.position = to;
    anim1.duration = 3.0;

When I run this, I see two blue circles moving. I want to see one circle moving from (x,y) to (x+dx,y+dy). Could someone clue me in on what I'm doing wrong?

thanks


Solution

  • It only shows one circle for me but I added the animation to the layer (which your code sample doesn't do) like this (after your last line of code):

    [l addAnimation:anim1 forKey:@"myNumberOneAnimation"];
    

    Without that line of code you get an implicit animation from setting the position of the layer. Changing animatable properties of layers that aren't associated with a view causes implicit animations. When you on the other hand explicitly animate the position by adding the animation to the layer it will show instead of the implicit animation.

    You can also configure the animation looks before it begins and after it finishes by changing the fillMode like this:

    anim1.fillMode = kCAFillModeBoth;
    

    If adding these lines doesn't fix the problem then it's somewhere else in your code. If so, please post more of the code where you are animating or changing the properties of the "l" layer.