首先将我的图层从一点移动到另一点我使用该代码:
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'中的代码时: 我的图层从第一个坐标移动到最后一个,就像它不知道之间的位置:/
答案 0 :(得分:3)
这是错误的:
[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
上设置代理。