【问题标题】:CAKeyFrameAnimation with different time duration on a particular UIBezierPath?在特定 UIBezierPath 上具有不同持续时间的 CAKeyFrameAnimation?
【发布时间】:2014-07-23 08:25:45
【问题描述】:

我想将图像动画到 UIBezierPath 上,持续时间为 12 秒。我为此使用 CAKeyframeAnimation。我的问题是我想动画图像从起点到 firstPoint 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"];

【问题讨论】:

    标签: ios7 xcode5 core-animation uibezierpath


    【解决方案1】:

    您的动画缺少一些内容。具体来说,您没有在您的CAKeyframeAnimation 上设置任何keyTimes 或值。即使它们是可选的,Core Animation 也不知道您希望在 2 秒后更改值,然后在 4 秒后再次更改。你必须告诉动画你想要什么。

    为此,您需要两个长度相等的NSArrays。第一个将关键帧的时间作为动画总时间的一个因素

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

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

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-10-01
      • 2012-11-17
      • 2020-11-30
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      相关资源
      最近更新 更多