到达第一个caanimation点后调用自定义函数

时间:2011-07-19 08:28:29

标签: iphone objective-c uiimage caanimation cakeyframeanimation

我想从右边(屏幕外)到中间,然后从中间到左边(屏幕外)滑动uiimage。当图像到达(动画路径的第一个点)中间时我想调用自定义函数。我怎么能意识到这一点?

感谢您的帮助。

这就是我尝试过的东西,但它在中间稍微滞后(第二个动画的开头)。我认为最好有一个动画

我的代码:

- (void) animateFromRightToMiddlePath {

 CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
 pathAnimation.calculationMode = kCAAnimationPaced;
 pathAnimation.fillMode = kCAFillModeForwards;
 pathAnimation.removedOnCompletion = NO;
 pathAnimation.duration = 3;
 pathAnimation.repeatCount = 1;
 pathAnimation.delegate = self;
 [pathAnimation setValue:@"rightToMiddle" forKey:@"AnimationType"];


 CGMutablePathRef curvedPath = CGPathCreateMutable();
 CGPathMoveToPoint(curvedPath, NULL, x + (picture.size.width/2), 250);
 CGPathAddLineToPoint(curvedPath, NULL, (picture.size.width/2), 250);
 pathAnimation.path = curvedPath;
 CGPathRelease(curvedPath);
 imageView = [[UIImageView alloc] initWithImage:picture];
 imageView.tag = 1;
 imageView.frame = CGRectMake(1, 1, picture.size.width, picture.size.height);
 [self addSubview:imageView];
 [imageView.layer addAnimation:pathAnimation forKey:@"moveTheSquare"];

}

- (void) animateFromMiddleToLeftPath {

     CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
     pathAnimation.calculationMode = kCAAnimationPaced;
     pathAnimation.fillMode = kCAFillModeForwards;
     pathAnimation.removedOnCompletion = NO;
     pathAnimation.duration = 3; 
     pathAnimation.repeatCount = 1;
     pathAnimation.delegate = self;
     [pathAnimation setValue:@"middleToLeft" forKey:@"AnimationType"];

     CGMutablePathRef curvedPath = CGPathCreateMutable();
     CGPathMoveToPoint(curvedPath, NULL, (picture.size.width/2), 250);
     CGPathAddLineToPoint(curvedPath, NULL, -(picture.size.width/2), 250);
     pathAnimation.path = curvedPath;
     CGPathRelease(curvedPath);

     [imageView.layer addAnimation:pathAnimation forKey:@"moveTheSquare"];

}

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag{

    NSString *aniType = [theAnimation valueForKey:@"AnimationType"];

    if ([aniType isEqualToString:@"rightToMiddle"]) {

        [self animateFromMiddleToLeftPath];
     // CUSTOM FUNCTION CALL
    }

    if ([aniType isEqualToString:@"middleToLeft"]) {

//        [self animateFromRightToMiddlePath];

    }

}

1 个答案:

答案 0 :(得分:0)

模拟这种互动的方法如下:

  1. 您的图片根据自己的逻辑在屏幕上移动(固定动画,拖动它等);

  2. 定义一个计时器,以便在每个刻度处调用一个处理函数;此处理程序负责(在您的特定情况下)检查图像的位置;

  3. 当位置符合您的要求时,处理程序会触发您的其他功能。

  4. 这看起来很复杂,但事实并非如此。它允许您以模块化和可重用的方式解决此问题,并且它受到游戏如何处理此类问题的启发。