【问题标题】:Delay before repeating a CAAnimation重复 CAAnimation 之前的延迟
【发布时间】:2013-10-23 22:10:46
【问题描述】:

你有一个简单的核心动画:

NSString *keyPath2 = @"anchorPoint.y";
CAKeyframeAnimation *kfa2 = [CAKeyframeAnimation animationWithKeyPath:keyPath2];
[kfa2 setValues:[NSArray arrayWithObjects:
                 [NSNumber numberWithFloat:-.05],
                 [NSNumber numberWithFloat:.1],
                 [NSNumber numberWithFloat:-.1],
                 [NSNumber numberWithFloat:.1],
                 [NSNumber numberWithFloat:-.05],
                 nil]];
//[kfa2 setRepeatCount:10];
[kfa2 setRepeatDuration:30];
[kfa2 setDuration:.35];
[kfa2 setAdditive:YES];
[kfa2 setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];

如何在动画重复之前设置延迟?

如果有人可以解释repeatCount和repeatDuration之间的区别。

我不想使用@selector。

谢谢大家。

【问题讨论】:

    标签: ios objective-c core-animation caanimation


    【解决方案1】:

    根据CAMediaTiming protocol's documentationrepeatCountrepeatDuration应该同时设置,repeatCount是什么意思,repeatDuration只是设置repeatCount的另一种方式,即repeatCount = repeatDuration / duration

    您可以通过添加额外的最后一个值来模拟CAKeyframeAnimation 的延迟。例如你有以下动画

    kfa.values = @[@1, @3, @7]; // Using object literal syntax (Google it!), the way to go
    kfa.keyTimes = @[@.0, @.5, @1]; // 0.5 = 5 / 10; 1 = 10 / 10;
    kfa.duration = 10; // 10 sec, for demonstration purpose
    

    现在您希望它在重复之前延迟 1 秒。只需将其更改为:

    kfa.values = @[@1, @3, @7, @7]; // An additional value
    kfa.keyTimes = @[@.0, @.4546, @.9091, @1]; // 0.4546 = 5 / 11; 0.9091 = 10 / 11; 1 = 11 / 11
    kfa.duration = 11;
    

    计算有点乱,但相当简单。

    【讨论】:

    • 谢谢你!完美,我会试试这个!
    【解决方案2】:

    您也可以使用 CAAnimationGroup。

    let scale         = CABasicAnimation(keyPath: "transform.scale") // or CAKeyFrameAnimation
    scale.toValue = 2.0
    scale.fillMode = kCAFillModeForwards
    scale.duration    = 0.4
    scale.beginTime   = 1.0 // Repeat delay.
    let scaleGroup = CAAnimationGroup()
    scaleGroup.duration    = scale.duration + scale.beginTime
    scaleGroup.fillMode    = kCAFillModeForwards
    scaleGroup.repeatCount = Float.infinity
    scaleGroup.animations  = [scale]
    scaleGroup.beginTime   = CACurrentMediaTime() + 0.8 // Initial delay.
    
    let view = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    view.backgroundColor = UIColor.orange
    
    let viewb = UIView(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
    viewb.backgroundColor = UIColor.blue
    view.addSubview(viewb)
    
    viewb.layer.add(scaleGroup, forKey: "")
    
    // If you want to try this on Playground
    PlaygroundPage.current.liveView = view
    

    【讨论】:

    • scale.beginTime 表示仅在第一个循环之前的延迟,而不是在每个动画循环之前。
    • @eXhausted 你能再试试示例代码吗?我修改了示例代码并在 Xcode8.2.1 Playground 上进行了尝试,我可以确认 scale.beginTime 应用于每个动画循环。
    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-25
    • 2013-07-07
    相关资源
    最近更新 更多