沿着一系列CGPoint移动图像

我有path存储在一个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){ }]; } } 

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

您的代码假定UIViewanimation在主线程中同步运行,而不是。

你似乎有两个select

  • 明确的CAKeyframeAnimation用于沿着任意数量的采样点(在它们之间插值)对CALayer进行animation处理,
  • 隐式recursionUIViewanimation,用于沿着一系列采样点对UIView进行animation处理(在它们之间进行插值)

前者会更有效率 – 我还以为我会告诉你们两个select。

CAKeyframeAnimation

 - (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"]; } 

UIViewanimation

 - (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]; } 

好的,你必须做的事情是将点的数组设置为类的属性,如animationPath 。 好吧,现在你将不得不注意UIViewanimation委托方法的委托方法(它实际上并不是一个不同的类,它只是类方法的委托)。

设置一个方法来调用setAnimationDidStopSelector:selector每当animation停止,所以在这里你会有这样的事情:

 //Inside the callback for setAnimationDidStopSelector if ([animationPath count] != 0){ //Go to next point CGPoint location = [[self.array objectAtIndex:0] CGPointValue]; [UIView animateWithDuration:0.1 animations:^{ self.imageView.center = location; } completion:^(BOOL finished){ }]; } else{ NSLog(@"Nowhere else to go, animation finished :D"); } 

所以只要确保以第一点开始animation。

据我记得UIView的animationpipe理其他线程的东西,所以这可能是为什么for语句不工作。