理解在图层上暂停和恢复动画 [英] Comprehend pause and resume animation on a layer
问题描述
我正在《 Core Animation编程指南》中学习"Animation",并且无法理解暂停并在图层上恢复动画.
I am studying Animation in Core Animation Programming Guide and I get stuck on comprehending pause and resume animation on a layer.
该文档告诉我如何在没有明确说明的情况下暂停和恢复动画.我认为关键是要了解什么是CAlayer
的timeOffset
和beginTime
方法.
The document tells me how to pause and resume animation without clear explanation. I think the key is to understand what is timeOffset
and beginTime
method of CAlayer
.
这些代码是暂停并恢复动画.在resumeLayer
方法中,layer.beginTime = timeSincePause;
这行确实让我感到困惑.
These code is pause and resume animation. In resumeLayer
method, layer.beginTime = timeSincePause;
this line really make me confused.
-(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;
}
任何帮助将不胜感激.
推荐答案
在CAMediaTiming的头文件中,我们可以看到以下代码:
In the header file of CAMediaTiming, we can see these codes:
/* The begin time of the object, in relation to its parent object, if
* applicable. Defaults to 0. */
@property CFTimeInterval beginTime;
/* The basic duration of the object. Defaults to 0. */
@property CFTimeInterval duration;
/* The rate of the layer. Used to scale parent time to local time, e.g.
* if rate is 2, local time progresses twice as fast as parent time.
* Defaults to 1. */
@property float speed;
/* 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;
重要的公式是:
t =(tp-开始)*速度+偏移量
此公式定义了全局时间(或父时间tp)如何映射到图层的本地时间.这个公式可以解释所有列出的代码:
This formula defines how the global time (or parent time, tp) maps to the local time of the layer. And this formula can explain everything of the listed codes:
- 在时间A,动画被暂停.设置速度= 0,并且timeOffset = pauseTime之后,该图层的本地时间等于pauseTime.而且本地时间不会再增加了,因为速度= 0;
- 在时间B,恢复动画.设置速度= 1.0,timeOffset = 0,beginTime = 0之后,图层的本地时间等于全局时间(或tp),即(timePause + timeSinacePause).但是我们需要动画从时间点#A开始,因此我们设置beginTime = timeSincePaused,然后图层的本地时间等于timePause.当然,这会导致动画从暂停点继续播放.
这篇关于理解在图层上暂停和恢复动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!