当前位置: 首页 > 工具软件 > CoreAnimation > 使用案例 >

Core Animation动画暂停和恢复

堵才哲
2023-12-01
-(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;
}

/* Additional offset in active local time. i.e. to convert from parent
* time tp to active local time t: t = (tp - begin) * speed + offset.
* One use of this is to "pause" a layer by setting `speed' to zero and
* `offset' to a suitable value. Defaults to 0. */
@property CFTimeInterval timeOffset;
/* The begin time of the object, in relation to its parent object, if
* applicable. Defaults to 0. */
@property CFTimeInterval beginTime

因为父对象的时间转换为有效本地时间是通过t = (tp - begin) * speed + offset计算的。

当暂停时,speed被设置为0.0,父对象的时间转换为有效本地时间需要设置offset为当前本地时间。

当恢复时,speed被设置为1.0,父对象的时间转换为有效本地时间需要设置offset为0.0,beginTime为经过的本地时间。因为tp(父对象时间)已经经过了timeSincePause,所以t = (tp - begin) * speed + offset的begin需要设置为timeSincePause。

 类似资料: