首先将图层从一个点移动到另一个点,我使用下面的代码:
CABasicAnimation *anim = [CABasicAnimation animationWithKeyPath:@"position"];
anim.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
anim.fromValue = [NSValue valueWithCGPoint:startPt];
anim.toValue = [NSValue valueWithCGPoint:endPt];
anim.repeatCount = 0;
anim.duration = 1.0;
[self.firstBall.ballLayer addAnimation:anim forKey:@"position"];
这是动画后清除第一个图层,并在其他地方重新绘制。
NSInteger firstBallIndex = [self.fieldsArray indexOfObject:self.firstBall];
NSInteger secondBallIndex = [self.fieldsArray indexOfObject:self.secondBall];
Field* ballFrom = [self.fieldsArray objectAtIndex:firstBallIndex];
Field* ballTo = [self.fieldsArray objectAtIndex:secondBallIndex];
ballTo.ballLayer = ballFrom.ballLayer;
CGPoint startPt = CGPointMake(self.firstBall.ballCoordinates.x,self.firstBall.ballCoordinates.y);
CGPoint endPt = CGPointMake(self.secondBall.ballCoordinates.x,self.secondBall.ballCoordinates.y);
ballTo.ballLayer.frame = CGRectMake(endPt.x, endPt.y, self.ballSize, self.ballSize);
ballFrom.ballLayer = nil;
[self.fieldsArray replaceObjectAtIndex:firstBallIndex withObject:ballFrom];
[self.fieldsArray replaceObjectAtIndex:secondBallIndex withObject:ballTo];
但接下来我尝试动画我的图层移动几次。所以我用这个代码:
CGMutablePathRef path = CGPathCreateMutable();
NSMutableArray * pathArray = [algorithm CreatePath];
CGPathMoveToPoint(path, NULL, self.firstBall.ballCoordinates.x, self.firstBall.ballCoordinates.y);
for (NSValue * pointValue in pathArray) {
CGPoint point = [pointValue CGPointValue];
Field* field = [self FindFieldWithPoint:point];
CGPathAddLineToPoint(path, NULL, field.ballCoordinates.x, field.ballCoordinates.y);
}
CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 2.0;
pathAnimation.path = path;
[UIView animateWithDuration:5
delay:5
options:UIViewAnimationOptionAllowUserInteraction
animations:^{
[self.firstBall.ballLayer addAnimation:pathAnimation forKey:@"position"];
}
completion:^ (BOOL finished)
{
if (finished) {
ballTo.ballLayer.frame = CGRectMake(endPt.x, endPt.y, self.ballSize, self.ballSize);
ballFrom.ballLayer = nil;
[self.fieldsArray replaceObjectAtIndex:firstBallIndex withObject:ballFrom];
[self.fieldsArray replaceObjectAtIndex:secondBallIndex withObject:ballTo];
}
}];
:
当我在'finished'中注释代码时:我的图层动画好了,从一个点移动到另一个点,但最后它会回到第一个坐标
当我取消'finished'中的注释代码时:我的图层从第一个坐标移动到最后一个,就像它不知道之间的位置:/
这是错误的:
[UIView animateWithDuration:5 // and so on
不要尝试以这种方式将图层动画与视图动画结合起来。只需将动画添加到图层中,然后退后。:)
CAKeyframeAnimation *pathAnimation =
[CAKeyframeAnimation animationWithKeyPath:@"position"];
pathAnimation.duration = 2.0;
pathAnimation.path = path;
[self.firstBall.ballLayer addAnimation:pathAnimation forKey:@"position"];
并立即设置您的最终位置以防止稍后的跳回:
ballTo.ballLayer.frame =
CGRectMake(endPt.x, endPt.y, self.ballSize, self.ballSize);
如果你仍然需要听到动画何时结束,那么在你的pathAnimation
上设置一个委托。