多次暂停和恢复 CAEmitterLayer

Pausing and Resuming CAEmitterLayer Multiple of Times

我有一个 CAEmitterLayer 实例,我想暂停然后恢复多次

我找到了使用两个 CAEmitterLayer 扩展函数执行此操作的多种方法:

public func pause() {
    speed = 0.0 // Freeze existing cells.
    timeOffset = convertTime(CACurrentMediaTime(), from: self)
    lifetime = 0.0 // Stop creating new cells.
}

public func resume() {
    speed = 1.0
    beginTime = convertTime(CACurrentMediaTime(), from: self) - timeOffset
    timeOffset = 0.0
    lifetime = 1.0
}

第一次使用 emitterLayer.pause()emitterLayer.resume() 效果很好。

但是,从第二次开始,每当我使用emitterLayer.pause()时,emitterCells的时间稍微向前跳

有人能帮我解决这个跳跃问题吗?

我需要调整 pause() 方法中的 timeOffset。这是暂停和恢复 CAEmitterLayer 实例的有效扩展:

extension CAEmitterLayer {

    /**
     Pauses a CAEmitterLayer.
     */
    public func pause() {
        speed = 0.0 // Freeze the CAEmitterCells.
        timeOffset = convertTime(CACurrentMediaTime(), from: self) - beginTime
        lifetime = 0.0 // Produce no new CAEmitterCells.
    }

    /**
     Resumes a paused CAEmitterLayer.
     */
    public func resume() {
        speed = 1.0 // Unfreeze the CAEmitterCells.
        beginTime = convertTime(CACurrentMediaTime(), from: self) - timeOffset
        timeOffset = 0.0
        lifetime = 1.0 // Produce CAEmitterCells at previous rate.
    }

}

用作:

var emitterLayer = CAEmitterLayer()
/// Configure as required

emitterLayer.pause()
emitterLayer.resume()