Resume CABasicAnimation using negative speed?

邮差的信 提交于 2021-02-19 02:55:20

问题


I resume my CABasicAnimation with the following code:

    CFTimeInterval pausedtime = layer.timeOffset;
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = [layer convertTime:CACurrentMediaTime() toLayer:nil] - pausedTime;

which is pretty straightforward. At the very end of this article the author states that with negative speed value animation reverses. I can't understand what timeOffset and beginTime should look like in this case?

P.S. I am aware that I can reverse animation by obtaining current values from presentation layer and setting toValue and fromValue. I want to figure out if it is possible with speed property.


回答1:


You will have problems with resuming an animation backwards with .timeOffset = 0. .timeOffset = 0 means that the animation is at its beginning. So, with reverse speed the animation will be finished immediately. Thus, if you, for example, have animation which is removed automatically on completion — it won't play anything: just will disappear.

CAAnimation has poor documentation indeed. And their example of resuming uses .beginTime property only. We can use .timeOffset property instead.

1. Set your layer's begin time to the current time of its container:

// set begin time to current time of superlayer to start immediately
let sTime = layer.superlayer?.convertTime(CACurrentMediaTime(), to: nil) ?? 0
layer.beginTime = sTime

2. Go to the moment of animation, where you want to resume, using .timeOffset:

// set starting point of animation to the current "progress"
layer.timeOffset = progress

Where progress is the time position you want to resume from in terms of animation duration. i.e. if you have an animation duration of 0.6 — then 0 ≤ progress ≤ 0.6.

3. Launch animation in reverse direction:

// set negative speed to have reverse animation
layer.speed = -1.0

Don't forget to remove animation on its completion, if needed.

This is the picture of how these settings are applied in fact:



来源:https://stackoverflow.com/questions/36338092/resume-cabasicanimation-using-negative-speed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!