如何在动画CABasicAnimation时改变速度

问题描述 投票:6回答:6

在我的应用程序中,我使用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;

   }
objective-c ios cocoa-touch ipad cabasicanimation
6个回答
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


2
投票

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

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

原帖:

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

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

1
投票

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

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

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


1
投票

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

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


0
投票

根据您的需要设定速度。

    a.duration=0.5;

试试这个...


0
投票

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

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

它可能也适用于您的情况,尝试一下。

© www.soinside.com 2019 - 2024. All rights reserved.