如何在动画CABasicAnimation时改变速度

时间:2012-06-26 10:29:33

标签: objective-c ios cocoa-touch ipad cabasicanimation

在我的应用程序中,我使用CABasicAnimation进行动画制作。我想动态更改动画的速度,所以我添加了一个滑块来改变速度。以下是我的动画代码。但是我无法改变速度,当我改变速度值时没有任何反应。

        CABasicAnimation * a = [CABasicAnimation animationWithKeyPath:@"position"];
    [a setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];

    CGPoint startPt = CGPointMake(self.view.bounds.size.width + displayLabel.bounds.size.width / 2,
                                  displayLabel.frame.origin.y);
    CGPoint endPt = CGPointMake(displayLabel.bounds.size.width / -2, displayLabel.frame.origin.y);

    [a setFromValue:[NSValue valueWithCGPoint:startPt]];
    [a setToValue:[NSValue valueWithCGPoint:endPt]];
    [a setAutoreverses:NO];
    [a setDuration:speeds];
    [a setRepeatCount:HUGE_VAL];
    [displayLabel.layer addAnimation:a forKey:@"rotationAnimation"];


    - (IBAction)speedSlider:(id)sender {

         speeds = slider.value;

   }

6 个答案:

答案 0 :(得分:6)

我认为改变速度的最佳方法是更改​​图层的时间系统

displayLabel.layer.timeOffset =
     [displayLabel.layer convertTime:CACurrentMediaTime() fromLayer:nil]; 
displayLabel.layer.beginTime = CACurrentMediaTime(); 
displayLabel.layer.speed= slider.value;

你可以看到这个提前。 https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreAnimation_guide/AdvancedAnimationTricks/AdvancedAnimationTricks.html#//apple_ref/doc/uid/TP40004514-CH8-SW2

答案 1 :(得分:2)

编辑:看起来你会遇到另一个问题:它不会look like你可以在正在运行的动画上改变这样的值。您必须删除当前动画并添加具有更改值的新动画。添加新动画时,可能需要注意防止卡纸效果。

从上面的主题中,你可以通过不重复动画来做到这一点,但是通过使用委托(see here)继续重新添加动画,并为下一个动画设置新的速度而是循环。

原帖:

您正在更改最初传入动画的值。这不会影响正在运行的动画。您需要获取对它的引用,并更改动画对象的duration属性。你的行动方法中有类似的东西:

CABasicAnimation *a = [displayLabel.layer animationForKey:@"rotationAnimation"];
a.duration = slider.value;

答案 2 :(得分:1)

我认为jrturton是正确的,你不能改变已经运行的动画的属性。但是你可以做的是将动画分成短段,并在滑块值改变时改变下一段的速度。

不是从A点到D点的动画,而是从A-B,然后是B-C,然后是C-D动画。使用父类的animationDidStop检查当前点,检查滑块值,然后启动下一个动画。

这可能会产生不稳定的动作,但是如果你使用非常小的片段,你可能会把它弄平。

答案 3 :(得分:1)

你应该停止动画并重新启动新的持续时间

但请记住注销fromValue和toValue,并使用旧的toValue作为新的fromValue来执行无缝更改

答案 4 :(得分:0)

根据需要设定速度。

    a.duration=0.5;

试试这个......

答案 5 :(得分:0)

如果您只想要自动滚动文本,那么您也可以使用一个类

http://blog.stormyprods.com/2009/10/simple-scrolling-uilabel-for-iphone.html

它可能也适用于你的情况,试试吧。