沿着一系列CGPoints移动图像 [英] Moving an image along a series of CGPoints
问题描述
我将路径存储在CGPoints数组中,我想移动图像。这是我到目前为止的一般代码:
I have path stored in an array of CGPoints which I'd like to move an image along. Here's the general code I have so far:
-(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循环运行得非常快,所以你只看到最后几点的动画。我不确定如何更好地设计这个。理想情况下,我可以做些什么来确保一个动画在另一个动画开始之前完成?我不应该使用for循环吗?谢谢
The problem is the for loop runs extremely fast, so you only see the animation on the last points. I'm unsure of how to better design this. Ideally, what could I do to make sure one animation finishes before the other begins? Should I not use a for loop? Thanks
推荐答案
您的代码假设UIView动画在主线程中同步运行,而不是。
Your code assumes that UIView animations run synchronously in the main thread, which they do not.
您似乎有两个选择
- 明确
CAKeyframeAnimation
沿着任意数量的样本点(在它们之间插入)动画CALayer
- 隐式递归
UIView
沿着一系列样本点(在它们之间插入)动画UIView
的动画
- Explicit
CAKeyframeAnimation
for animating aCALayer
along any amount of sample points (interpolated between them) - Implicit recursive
UIView
animation for animating aUIView
along a series of sample points (interpolated between them)
前者会更有效率 - 我仍然认为我可以向你展示这两个选项。
The former would be much more efficient - still I thought I oould show you both options.
- (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"];
}
UIView动画
UIView Animation
- (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];
}
这篇关于沿着一系列CGPoints移动图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!