CAKeyFrameAnimation在特定UIBezierPath上具有不同的持续时间?

时间:2014-07-23 08:25:46

标签: ios7 xcode5 core-animation uibezierpath

我想将图像设置为UIBezierPath的动画,持续时间为12秒。我正在使用CAKeyframeAnimation。我的问题是我想要从起始点到第一点动画图像2秒,从第一点到第二点动画4秒,从第二点到第三点动画4秒,从第三点到终点动画2秒。我怎样才能做到这一点?这是我的代码。

CGPoint startingpoint = CGPointMake(self.bounds.origin.x + 98, self.bounds.size.height -20);
CGPoint firstPoint = CGPointMake(startingpoint.x + 20,startingpoint.y);
CGPoint secondpoint = CGPointMake(firstPoint.x + 30,firstPoint.y - 80);
CGPoint thirdpoint = CGPointMake(secondpoint.x + 50, secondpoint.y + 80);
CGPoint endPoints = CGPointMake(thirdpoint.x + 20,thirdpoint.y);

UIBezierPath *path = [UIBezierPath bezierPath];
[path moveToPoint:startingpoint];
[path addLineToPoint:firstPoint];
[path addLineToPoint:secondpoint];
[path addLineToPoint:thirdpoint];
[path addLineToPoint:endPoints];

CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = [[UIColor whiteColor] CGColor];
shapeLayer.lineWidth = 3.0;
shapeLayer.fillColor = [[UIColor clearColor] CGColor];
[self.layer addSublayer:shapeLayer];

CAKeyframeAnimation *animation1 = [CAKeyframeAnimation animationWithKeyPath:@"position"];
animation1.duration = 10;
animation1.path = path.CGPath;
animation1.autoreverses = NO;
animation1.repeatCount = 0;
[myImageView.layer addAnimation:animation1 forKey:@"position"];

1 个答案:

答案 0 :(得分:1)

你在动画上遗漏了一些东西。具体而言,您未在keyTimes上设置任何CAKeyframeAnimation或值。即使它们是可选的,Core Animation也不知道您希望在2秒后更改值,然后在4秒后再次更改。你必须告诉动画你想要什么。

要做到这一点,你需要两个长度相等的NSArray。第一个将关键帧的时间作为动画总时间的一个因素

CFTimeInterval d = 12.0f; // 12 seconds total time
NSArray * keyTimes = @[@(0), @(2/d), @(6/d), @(10/d), @(1.0)];

另一个是keyTimes对应的值列表(在这种情况下,CGPoint包含在NSValues中,因为你是动画CGPoint类型的属性):

NSArray * pointValues = @[[NSValue valueWithCGPoint:startingPoint], [NSValue valueWithCGPoint:firstPoint], [NSValue valueWithCGPoint:secondPoint], [NSValue valueWithCGPoint:thirdPoint], [NSValue valueWithCGPoint:endPoint]];

最后在动画上设置它们:

animation1.keyTimes = keyTimes;
animation1.values = values;

如果你想真正想象,你还可以为所提供的关键时间之间的每个值变化的时间指定一个n-1长度的定时函数数组:

CAMediaTimingFunction * linear = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
CAMediaTimingFunction * easeIn = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseIn];
CAMediaTimingFunction * fastEaseInOut = [CAMediaTimingFunction functionWithControlPoints:0.30f :0.92f :0.86f :0.95f];

NSArray * timingFunctions = @[easeIn, linear, linear, fastEaseInOut];
animation1.timingFunctions = timingFunctions;