CAKeyframeanimation moves a UIView along a path

Here is my code to move UIview 30px down and then to y = 10, but this animation does not work. This is my first attempt at creating a CAKeyframeAnimation, so someone can help me write it correctly. I also want my object not to return to its original location, but stay where the animation ended.

CGMutablePathRef thePath = CGPathCreateMutable();
    CGPathAddRect(thePath, NULL, CGRectMake(self.logo.frame.origin.x, self.logo.frame.origin.y, self.logo.frame.size.width, self.logo.frame.size.height));
    CGPathAddRect(thePath, NULL, CGRectMake(self.logo.frame.origin.x, self.logo.frame.origin.y-30, self.logo.frame.size.width, self.logo.frame.size.height));
    CGPathAddRect(thePath, NULL, CGRectMake(self.logo.frame.origin.x, 100, self.logo.frame.size.width, self.logo.frame.size.height));


    CAKeyframeAnimation* AniLoc = [CAKeyframeAnimation animationWithKeyPath:@"frame"];
    AniLoc.path = thePath;
    AniLoc.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    AniLoc.keyTimes= [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:0.3f],
                      [NSNumber numberWithFloat:1.0f],nil];
    AniLoc.duration = 2.0;

    CFRelease(thePath);

    [self.logo.layer addAnimation:AniLoc forKey:nil];
+5
source share
1 answer

I'm not quite sure why your method does not work, but I can offer a different solution. Instead of managing the frame, you can change the position key to move the UIView:

    CGMutablePathRef thePath = CGPathCreateMutable();
    CGPathMoveToPoint(thePath, NULL, self.logo.frame.origin.x, self.logo.frame.origin.y); // initial point, notice the function
    CGPathAddLineToPoint(thePath, NULL, self.logo.frame.origin.x - 30, self.logo.frame.origin.y);
    CGPathAddLineToPoint(thePath, NULL, 100, self.logo.frame.origin.y);

    CAKeyframeAnimation* AniLoc = [CAKeyframeAnimation animationWithKeyPath:@"position"]; // notice key change

    // rest is the same
    AniLoc.path = thePath;
    AniLoc.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
    AniLoc.keyTimes= [NSArray arrayWithObjects:[NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:0.3f],
                      [NSNumber numberWithFloat:1.0f],nil];
    AniLoc.duration = 2.0;

    CFRelease(thePath);

    [self.logo.layer addAnimation:AniLoc forKey:nil];

Hope this helps you.

+1
source

All Articles