Skip to content

Commit

Permalink
Merge pull request onevcat#861 from mliberatore/fix-loop-counting
Browse files Browse the repository at this point in the history
Fixes Gif Loop Counting and Frame Skipping
  • Loading branch information
onevcat authored Feb 14, 2018
2 parents 43ec2d2 + 5c42022 commit 0616898
Showing 1 changed file with 13 additions and 9 deletions.
22 changes: 13 additions & 9 deletions Sources/AnimatedImageView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ class Animator {
fileprivate let maxTimeStep: TimeInterval = 1.0
fileprivate var frameCount = 0
fileprivate var currentFrameIndex = 0
fileprivate var currentFrameIndexInBuffer = 0
fileprivate var currentPreloadIndex = 0
fileprivate var timeSinceLastFrameChange: TimeInterval = 0.0
fileprivate var needsPrescaling = true
Expand All @@ -315,7 +316,7 @@ class Animator {
private var loopCount = 0

var currentFrame: UIImage? {
return frame(at: currentFrameIndex)
return frame(at: currentFrameIndexInBuffer)
}

var isReachMaxRepeatCount: Bool {
Expand Down Expand Up @@ -380,7 +381,7 @@ class Animator {
let frameToProcess = min(frameCount, maxFrameCount)
animatedFrames.reserveCapacity(frameToProcess)
animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
currentPreloadIndex = (frameToProcess + 1) % frameCount
currentPreloadIndex = (frameToProcess + 1) % frameCount - 1
}

private func prepareFrame(at index: Int) -> AnimatedFrame {
Expand Down Expand Up @@ -426,21 +427,24 @@ class Animator {
*/
func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
timeSinceLastFrameChange += min(maxTimeStep, duration)
guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration, frameDuration <= timeSinceLastFrameChange else {
guard let frameDuration = animatedFrames[safe: currentFrameIndexInBuffer]?.duration, frameDuration <= timeSinceLastFrameChange else {
return false
}

timeSinceLastFrameChange -= frameDuration

let lastFrameIndex = currentFrameIndex
currentFrameIndex += 1
currentFrameIndex = currentFrameIndex % animatedFrames.count

let lastFrameIndex = currentFrameIndexInBuffer
currentFrameIndexInBuffer += 1
currentFrameIndexInBuffer = currentFrameIndexInBuffer % animatedFrames.count
if animatedFrames.count < frameCount {
preloadFrameAsynchronously(at: lastFrameIndex)
}

if currentFrameIndex == 0 {

currentFrameIndex += 1

if currentFrameIndex == frameCount {
currentFrameIndex = 0
currentRepeatCount += 1

delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
Expand Down

0 comments on commit 0616898

Please sign in to comment.