Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pause and resume CABasicAnimation for Loading Screen?

I have implemented a LoadingLayer class that has some animating elements (2 to be exact) which are animated with CABasicAnimation. Now, this loading screen view persists throughout the whole application. Does hiding the view stop all animations ? Or let me rephrase that: Is there a lot of memory I have to be worried about or could that potentially cause lags ? I tried to use the -pauseLayer: and -resumeLayer: methods but they caused some problems due to multithreading in my application. Is it therefore ok just to hide and show the loading screen with its animations running all the time ?

like image 330
the_critic Avatar asked Apr 03 '13 14:04

the_critic


2 Answers

https://developer.apple.com/library/content/qa/qa1673/_index.html

-(void)pauseLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer convertTime:CACurrentMediaTime() fromLayer:nil];
    layer.speed = 0.0;
    layer.timeOffset = pausedTime;
}

-(void)resumeLayer:(CALayer*)layer
{
    CFTimeInterval pausedTime = [layer timeOffset];
    layer.speed = 1.0;
    layer.timeOffset = 0.0;
    layer.beginTime = 0.0;
    CFTimeInterval timeSincePause = [layer convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    layer.beginTime = timeSincePause;
}
like image 135
Nico Avatar answered Nov 18 '22 05:11

Nico


Here is the swift 3 version of Nico's answer.

Hope helps!

fileprivate func pauseLayer(layer: CALayer) {
    let pausedTime = layer.convertTime(CACurrentMediaTime(), from: nil)
    layer.speed = 0.0
    layer.timeOffset = pausedTime
}

fileprivate func resumeLayer(layer: CALayer) {
    let pausedTime = layer.timeOffset
    layer.speed = 1.0
    layer.timeOffset = 0.0
    layer.beginTime = 0.0
    let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
    layer.beginTime = timeSincePause
}
like image 24
Victor Avatar answered Nov 18 '22 06:11

Victor