首先要从一个点到另一个点移动我的层,我使用该代码:
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];
}
}];
现在:
当我在“完成”中评论代码时:我的图层动画正常,从一个点移动到另一个点,但最后它回到第一个坐标
当我在“完成”中取消注释代码时:我的图层从第一个坐标移动到最后一个坐标,就像它不知道之间的位置:/