沿着一系列CGPoints移动图像

use*_*946 5 iphone core-animation uikit ipad ios

我有一个路径存储在一个CGPoints数组中,我想移动一个图像.这是我到目前为止的一般代码:

-(void)movePic:(id)sender{
    for(int i = 0; i < self.array.count; i++){
        CGPoint location = [[self.array objectAtIndex:i] CGPointValue];
        [UIView animateWithDuration:0.1 animations:^{
            self.imageView.center = location;
        } completion:^(BOOL finished){
        }];
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是for循环运行得非常快,所以你只能在最后几点看到动画.我不确定如何更好地设计这个.理想情况下,我可以做些什么来确保一个动画在另一个动画开始之前完成?我不应该使用for循环吗?谢谢

Til*_*ill 4

您的代码假设 UIView 动画在主线程中同步运行,但事实并非如此。

你似乎有两个选择

  • 显式用于沿任意数量的采样点(在它们之间插值)CAKeyframeAnimation制作动画CALayer
  • 隐式递归UIView动画,用于UIView沿一系列样本点(在它们之间插值)进行动画处理

前者会更有效率 - 但我仍然认为我应该向您展示这两种选择。

CA关键帧动画

- (void)movePic:(id)sender
{
    //create a mutable core-graphics path
    CGMutablePathRef path = CGPathCreateMutable();
    for(int i = 0; i < self.array.count; i++)
    {
        CGPoint location = [[self.array objectAtIndex:index] CGPointValue];
        CGPathAddLineToPoint(path, nil, location.x, location.y);
    }
    //create a new keyframe animation
    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    //add our path to it
    pathAnimation.path = path;
    //be nice to the system
    CGPathRelease(path);
    //setup some more animation parameters
    pathAnimation.duration = 0.1 * self.array.count;
    //add the animation to our imageView's layer (which will start the animation)
    [self.imageView.layer addAnimation:pathAnimation forKey:@"pathAnimation"];
}
Run Code Online (Sandbox Code Playgroud)

UIView动画

- (void)movePicToPointAtIndex:(unsigned int)index
{
    //safeguard check...
    if ([self.array count] <= index)
        return;
    //get the next location
    CGPoint location = [[self.array objectAtIndex:index] CGPointValue];
    //animate the imageView center towards that location
    [UIView animateWithDuration:0.1 
                          delay:0.0 
                        options:UIViewAnimationOptionBeginFromCurrentState | UIViewAnimationOptionAllowUserInteraction
                     animations:^{
        self.imageView.center = location;
    } completion:^(BOOL finished){
        //we are done with that animation, now go to the next one...
        [self movePicToPointAtIndex:index+1];
    }];
}

- (void)movePic:(id)sender
{
    [self movePicToPointAtIndex:0];
}
Run Code Online (Sandbox Code Playgroud)