AnimatedImageView.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733
  1. //
  2. // AnimatableImageView.swift
  3. // Kingfisher
  4. //
  5. // Created by bl4ckra1sond3tre on 4/22/16.
  6. //
  7. // The AnimatableImageView, AnimatedFrame and Animator is a modified version of
  8. // some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
  9. //
  10. // The MIT License (MIT)
  11. //
  12. // Copyright (c) 2019 Reda Lemeden.
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining a copy of
  15. // this software and associated documentation files (the "Software"), to deal in
  16. // the Software without restriction, including without limitation the rights to
  17. // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  18. // the Software, and to permit persons to whom the Software is furnished to do so,
  19. // subject to the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be included in all
  22. // copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  25. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  26. // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  27. // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  28. // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  29. // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. // The name and characters used in the demo of this software are property of their
  32. // respective owners.
  33. #if !os(watchOS)
  34. #if canImport(UIKit)
  35. import UIKit
  36. import ImageIO
  37. /// Protocol of `AnimatedImageView`.
  38. public protocol AnimatedImageViewDelegate: AnyObject {
  39. /// Called after the animatedImageView has finished each animation loop.
  40. ///
  41. /// - Parameters:
  42. /// - imageView: The `AnimatedImageView` that is being animated.
  43. /// - count: The looped count.
  44. func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
  45. /// Called after the `AnimatedImageView` has reached the max repeat count.
  46. ///
  47. /// - Parameter imageView: The `AnimatedImageView` that is being animated.
  48. func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
  49. }
  50. extension AnimatedImageViewDelegate {
  51. public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
  52. public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
  53. }
  54. let KFRunLoopModeCommon = RunLoop.Mode.common
  55. /// Represents a subclass of `UIImageView` for displaying animated image.
  56. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
  57. /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
  58. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
  59. /// view to load GIF data, you could give this class a try.
  60. ///
  61. /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
  62. /// it would be fairly easy to switch between them.
  63. open class AnimatedImageView: UIImageView {
  64. /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  65. class TargetProxy {
  66. private weak var target: AnimatedImageView?
  67. init(target: AnimatedImageView) {
  68. self.target = target
  69. }
  70. @objc func onScreenUpdate() {
  71. target?.updateFrameIfNeeded()
  72. }
  73. }
  74. /// Enumeration that specifies repeat count of GIF
  75. public enum RepeatCount: Equatable {
  76. case once
  77. case finite(count: UInt)
  78. case infinite
  79. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  80. switch (lhs, rhs) {
  81. case let (.finite(l), .finite(r)):
  82. return l == r
  83. case (.once, .once),
  84. (.infinite, .infinite):
  85. return true
  86. case (.once, .finite(let count)),
  87. (.finite(let count), .once):
  88. return count == 1
  89. case (.once, _),
  90. (.infinite, _),
  91. (.finite, _):
  92. return false
  93. }
  94. }
  95. }
  96. // MARK: - Public property
  97. /// Whether automatically play the animation when the view become visible. Default is `true`.
  98. public var autoPlayAnimatedImage = true
  99. /// The count of the frames should be preloaded before shown.
  100. public var framePreloadCount = 10
  101. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  102. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
  103. /// Default is `true`.
  104. public var needsPrescaling = true
  105. /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
  106. /// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
  107. public var backgroundDecode = true
  108. /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
  109. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  110. public var runLoopMode = KFRunLoopModeCommon {
  111. willSet {
  112. guard runLoopMode != newValue else { return }
  113. stopAnimating()
  114. displayLink.remove(from: .main, forMode: runLoopMode)
  115. displayLink.add(to: .main, forMode: newValue)
  116. startAnimating()
  117. }
  118. }
  119. /// The repeat count. The animated image will keep animate until it the loop count reaches this value.
  120. /// Setting this value to another one will reset current animation.
  121. ///
  122. /// Default is `.infinite`, which means the animation will last forever.
  123. public var repeatCount = RepeatCount.infinite {
  124. didSet {
  125. if oldValue != repeatCount {
  126. reset()
  127. setNeedsDisplay()
  128. layer.setNeedsDisplay()
  129. }
  130. }
  131. }
  132. /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
  133. public weak var delegate: AnimatedImageViewDelegate?
  134. /// The `Animator` instance that holds the frames of a specific image in memory.
  135. public private(set) var animator: Animator?
  136. // MARK: - Private property
  137. // Dispatch queue used for preloading images.
  138. private lazy var preloadQueue: DispatchQueue = {
  139. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  140. }()
  141. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  142. private var isDisplayLinkInitialized: Bool = false
  143. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  144. private lazy var displayLink: CADisplayLink = {
  145. isDisplayLinkInitialized = true
  146. let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  147. displayLink.add(to: .main, forMode: runLoopMode)
  148. displayLink.isPaused = true
  149. return displayLink
  150. }()
  151. // MARK: - Override
  152. override open var image: KFCrossPlatformImage? {
  153. didSet {
  154. if image != oldValue {
  155. reset()
  156. }
  157. setNeedsDisplay()
  158. layer.setNeedsDisplay()
  159. }
  160. }
  161. open override var isHighlighted: Bool {
  162. get {
  163. super.isHighlighted
  164. }
  165. set {
  166. // Highlighted image is unsupported for animated images.
  167. // See https://github.com/onevcat/Kingfisher/issues/1679
  168. if displayLink.isPaused {
  169. super.isHighlighted = newValue
  170. }
  171. }
  172. }
  173. // Workaround for Apple xcframework creating issue on Apple TV in Swift 5.8.
  174. // https://github.com/apple/swift/issues/66015
  175. #if os(tvOS)
  176. public override init(image: UIImage?, highlightedImage: UIImage?) {
  177. super.init(image: image, highlightedImage: highlightedImage)
  178. }
  179. required public init?(coder: NSCoder) {
  180. super.init(coder: coder)
  181. }
  182. init() {
  183. super.init(frame: .zero)
  184. }
  185. #endif
  186. deinit {
  187. if isDisplayLinkInitialized {
  188. displayLink.invalidate()
  189. }
  190. }
  191. override open var isAnimating: Bool {
  192. if isDisplayLinkInitialized {
  193. return !displayLink.isPaused
  194. } else {
  195. return super.isAnimating
  196. }
  197. }
  198. /// Starts the animation.
  199. override open func startAnimating() {
  200. guard !isAnimating else { return }
  201. guard let animator = animator else { return }
  202. guard !animator.isReachMaxRepeatCount else { return }
  203. displayLink.isPaused = false
  204. }
  205. /// Stops the animation.
  206. override open func stopAnimating() {
  207. super.stopAnimating()
  208. if isDisplayLinkInitialized {
  209. displayLink.isPaused = true
  210. }
  211. }
  212. override open func display(_ layer: CALayer) {
  213. layer.contents = animator?.currentFrameImage?.cgImage ?? image?.cgImage
  214. }
  215. override open func didMoveToWindow() {
  216. super.didMoveToWindow()
  217. didMove()
  218. }
  219. override open func didMoveToSuperview() {
  220. super.didMoveToSuperview()
  221. didMove()
  222. }
  223. // This is for back compatibility that using regular `UIImageView` to show animated image.
  224. override func shouldPreloadAllAnimation() -> Bool {
  225. return false
  226. }
  227. // Reset the animator.
  228. private func reset() {
  229. animator = nil
  230. if let image = image, let frameSource = image.kf.frameSource {
  231. #if os(visionOS)
  232. let targetSize = bounds.scaled(UITraitCollection.current.displayScale).size
  233. #else
  234. var scale: CGFloat = 0
  235. if #available(iOS 13.0, *) {
  236. let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
  237. scale = windowScene?.screen.scale ?? .zero
  238. } else {
  239. scale = UIScreen.main.scale
  240. }
  241. let targetSize = bounds.scaled(scale).size
  242. #endif
  243. let animator = Animator(
  244. frameSource: frameSource,
  245. contentMode: contentMode,
  246. size: targetSize,
  247. imageSize: image.kf.size,
  248. imageScale: image.kf.scale,
  249. framePreloadCount: framePreloadCount,
  250. repeatCount: repeatCount,
  251. preloadQueue: preloadQueue)
  252. animator.delegate = self
  253. animator.needsPrescaling = needsPrescaling
  254. animator.backgroundDecode = backgroundDecode
  255. animator.prepareFramesAsynchronously()
  256. self.animator = animator
  257. }
  258. didMove()
  259. }
  260. private func didMove() {
  261. if autoPlayAnimatedImage && animator != nil {
  262. if let _ = superview, let _ = window {
  263. startAnimating()
  264. } else {
  265. stopAnimating()
  266. }
  267. }
  268. }
  269. /// Update the current frame with the displayLink duration.
  270. private func updateFrameIfNeeded() {
  271. guard let animator = animator else {
  272. return
  273. }
  274. guard !animator.isFinished else {
  275. stopAnimating()
  276. delegate?.animatedImageViewDidFinishAnimating(self)
  277. return
  278. }
  279. let duration: CFTimeInterval
  280. // CA based display link is opt-out from ProMotion by default.
  281. // So the duration and its FPS might not match.
  282. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  283. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  284. // cause the preferredFramesPerSecond being 0
  285. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  286. if preferredFramesPerSecond == 0 {
  287. duration = displayLink.duration
  288. } else {
  289. // Some devices (like iPad Pro 10.5) will have a different FPS.
  290. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  291. }
  292. animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
  293. if hasNewFrame {
  294. self?.layer.setNeedsDisplay()
  295. }
  296. }
  297. }
  298. }
  299. protocol AnimatorDelegate: AnyObject {
  300. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  301. }
  302. extension AnimatedImageView: AnimatorDelegate {
  303. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  304. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  305. }
  306. }
  307. extension AnimatedImageView {
  308. // Represents a single frame in a GIF.
  309. struct AnimatedFrame {
  310. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  311. let image: UIImage?
  312. // The duration that this frame should remain active.
  313. let duration: TimeInterval
  314. // A placeholder frame with no image assigned.
  315. // Used to replace frames that are no longer needed in the animation.
  316. var placeholderFrame: AnimatedFrame {
  317. return AnimatedFrame(image: nil, duration: duration)
  318. }
  319. // Whether this frame instance contains an image or not.
  320. var isPlaceholder: Bool {
  321. return image == nil
  322. }
  323. // Returns a new instance from an optional image.
  324. //
  325. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  326. // - returns: An `AnimatedFrame` instance.
  327. func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
  328. return AnimatedFrame(image: image, duration: duration)
  329. }
  330. }
  331. }
  332. extension AnimatedImageView {
  333. // MARK: - Animator
  334. /// An animator which used to drive the data behind `AnimatedImageView`.
  335. public class Animator {
  336. private let size: CGSize
  337. private let imageSize: CGSize
  338. private let imageScale: CGFloat
  339. /// The maximum count of image frames that needs preload.
  340. public let maxFrameCount: Int
  341. private let frameSource: ImageFrameSource
  342. private let maxRepeatCount: RepeatCount
  343. private let maxTimeStep: TimeInterval = 1.0
  344. private let animatedFrames = SafeArray<AnimatedFrame>()
  345. private var frameCount = 0
  346. private var timeSinceLastFrameChange: TimeInterval = 0.0
  347. private var currentRepeatCount: UInt = 0
  348. var isFinished: Bool = false
  349. var needsPrescaling = true
  350. var backgroundDecode = true
  351. weak var delegate: AnimatorDelegate?
  352. // Total duration of one animation loop
  353. var loopDuration: TimeInterval = 0
  354. /// The image of the current frame.
  355. public var currentFrameImage: UIImage? {
  356. return frame(at: currentFrameIndex)
  357. }
  358. /// The duration of the current active frame duration.
  359. public var currentFrameDuration: TimeInterval {
  360. return duration(at: currentFrameIndex)
  361. }
  362. /// The index of the current animation frame.
  363. public internal(set) var currentFrameIndex = 0 {
  364. didSet {
  365. previousFrameIndex = oldValue
  366. }
  367. }
  368. var previousFrameIndex = 0 {
  369. didSet {
  370. preloadQueue.async {
  371. self.updatePreloadedFrames()
  372. }
  373. }
  374. }
  375. var isReachMaxRepeatCount: Bool {
  376. switch maxRepeatCount {
  377. case .once:
  378. return currentRepeatCount >= 1
  379. case .finite(let maxCount):
  380. return currentRepeatCount >= maxCount
  381. case .infinite:
  382. return false
  383. }
  384. }
  385. /// Whether the current frame is the last frame or not in the animation sequence.
  386. public var isLastFrame: Bool {
  387. return currentFrameIndex == frameCount - 1
  388. }
  389. var preloadingIsNeeded: Bool {
  390. return maxFrameCount < frameCount - 1
  391. }
  392. var contentMode = UIView.ContentMode.scaleToFill
  393. private lazy var preloadQueue: DispatchQueue = {
  394. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  395. }()
  396. /// Creates an animator with image source reference.
  397. ///
  398. /// - Parameters:
  399. /// - source: The reference of animated image.
  400. /// - mode: Content mode of the `AnimatedImageView`.
  401. /// - size: Size of the `AnimatedImageView`.
  402. /// - imageSize: Size of the `KingfisherWrapper`.
  403. /// - imageScale: Scale of the `KingfisherWrapper`.
  404. /// - count: Count of frames needed to be preloaded.
  405. /// - repeatCount: The repeat count should this animator uses.
  406. /// - preloadQueue: Dispatch queue used for preloading images.
  407. convenience init(imageSource source: CGImageSource,
  408. contentMode mode: UIView.ContentMode,
  409. size: CGSize,
  410. imageSize: CGSize,
  411. imageScale: CGFloat,
  412. framePreloadCount count: Int,
  413. repeatCount: RepeatCount,
  414. preloadQueue: DispatchQueue) {
  415. let frameSource = CGImageFrameSource(data: nil, imageSource: source, options: nil)
  416. self.init(frameSource: frameSource,
  417. contentMode: mode,
  418. size: size,
  419. imageSize: imageSize,
  420. imageScale: imageScale,
  421. framePreloadCount: count,
  422. repeatCount: repeatCount,
  423. preloadQueue: preloadQueue)
  424. }
  425. /// Creates an animator with a custom image frame source.
  426. ///
  427. /// - Parameters:
  428. /// - frameSource: The reference of animated image.
  429. /// - mode: Content mode of the `AnimatedImageView`.
  430. /// - size: Size of the `AnimatedImageView`.
  431. /// - imageSize: Size of the `KingfisherWrapper`.
  432. /// - imageScale: Scale of the `KingfisherWrapper`.
  433. /// - count: Count of frames needed to be preloaded.
  434. /// - repeatCount: The repeat count should this animator uses.
  435. /// - preloadQueue: Dispatch queue used for preloading images.
  436. init(frameSource source: ImageFrameSource,
  437. contentMode mode: UIView.ContentMode,
  438. size: CGSize,
  439. imageSize: CGSize,
  440. imageScale: CGFloat,
  441. framePreloadCount count: Int,
  442. repeatCount: RepeatCount,
  443. preloadQueue: DispatchQueue) {
  444. self.frameSource = source
  445. self.contentMode = mode
  446. self.size = size
  447. self.imageSize = imageSize
  448. self.imageScale = imageScale
  449. self.maxFrameCount = count
  450. self.maxRepeatCount = repeatCount
  451. self.preloadQueue = preloadQueue
  452. GraphicsContext.begin(size: imageSize, scale: imageScale)
  453. }
  454. deinit {
  455. resetAnimatedFrames()
  456. GraphicsContext.end()
  457. }
  458. /// Gets the image frame of a given index.
  459. /// - Parameter index: The index of desired image.
  460. /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded.
  461. public func frame(at index: Int) -> KFCrossPlatformImage? {
  462. return animatedFrames[index]?.image
  463. }
  464. public func duration(at index: Int) -> TimeInterval {
  465. return animatedFrames[index]?.duration ?? .infinity
  466. }
  467. func prepareFramesAsynchronously() {
  468. frameCount = frameSource.frameCount
  469. animatedFrames.reserveCapacity(frameCount)
  470. preloadQueue.async { [weak self] in
  471. self?.setupAnimatedFrames()
  472. }
  473. }
  474. func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
  475. incrementTimeSinceLastFrameChange(with: duration)
  476. if currentFrameDuration > timeSinceLastFrameChange {
  477. handler(false)
  478. } else {
  479. resetTimeSinceLastFrameChange()
  480. incrementCurrentFrameIndex()
  481. handler(true)
  482. }
  483. }
  484. private func setupAnimatedFrames() {
  485. resetAnimatedFrames()
  486. var duration: TimeInterval = 0
  487. (0..<frameCount).forEach { index in
  488. let frameDuration = frameSource.duration(at: index)
  489. duration += min(frameDuration, maxTimeStep)
  490. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  491. if index > maxFrameCount { return }
  492. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  493. }
  494. self.loopDuration = duration
  495. }
  496. private func resetAnimatedFrames() {
  497. animatedFrames.removeAll()
  498. }
  499. private func loadFrame(at index: Int) -> UIImage? {
  500. let resize = needsPrescaling && size != .zero
  501. let maxSize = resize ? size : nil
  502. guard let cgImage = frameSource.frame(at: index, maxSize: maxSize) else {
  503. return nil
  504. }
  505. if #available(iOS 15, tvOS 15, *) {
  506. // From iOS 15, a plain image loading causes iOS calling `-[_UIImageCGImageContent initWithCGImage:scale:]`
  507. // in ImageIO, which holds the image ref on the creating thread.
  508. // To get a workaround, create another image ref and use that to create the final image. This leads to
  509. // some performance loss, but there is little we can do.
  510. // https://github.com/onevcat/Kingfisher/issues/1844
  511. guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage),
  512. let decodedImageRef = cgImage.decoded(on: context, scale: imageScale)
  513. else {
  514. return KFCrossPlatformImage(cgImage: cgImage)
  515. }
  516. return KFCrossPlatformImage(cgImage: decodedImageRef)
  517. } else {
  518. let image = KFCrossPlatformImage(cgImage: cgImage)
  519. if backgroundDecode {
  520. guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else {
  521. return image
  522. }
  523. return image.kf.decoded(on: context)
  524. } else {
  525. return image
  526. }
  527. }
  528. }
  529. private func updatePreloadedFrames() {
  530. guard preloadingIsNeeded else {
  531. return
  532. }
  533. let previousFrame = animatedFrames[previousFrameIndex]
  534. animatedFrames[previousFrameIndex] = previousFrame?.placeholderFrame
  535. // ensure the image dealloc in main thread
  536. defer {
  537. if let image = previousFrame?.image {
  538. DispatchQueue.main.async {
  539. _ = image
  540. }
  541. }
  542. }
  543. preloadIndexes(start: currentFrameIndex).forEach { index in
  544. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  545. if !currentAnimatedFrame.isPlaceholder { return }
  546. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  547. }
  548. }
  549. private func incrementCurrentFrameIndex() {
  550. let wasLastFrame = isLastFrame
  551. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  552. if isLastFrame {
  553. currentRepeatCount += 1
  554. if isReachMaxRepeatCount {
  555. isFinished = true
  556. // Notify the delegate here because the animation is stopping.
  557. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  558. }
  559. } else if wasLastFrame {
  560. // Notify the delegate that the loop completed
  561. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  562. }
  563. }
  564. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  565. timeSinceLastFrameChange += min(maxTimeStep, duration)
  566. }
  567. private func resetTimeSinceLastFrameChange() {
  568. timeSinceLastFrameChange -= currentFrameDuration
  569. }
  570. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  571. return (frameIndex + value) % frameCount
  572. }
  573. private func preloadIndexes(start index: Int) -> [Int] {
  574. let nextIndex = increment(frameIndex: index)
  575. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  576. if lastIndex >= nextIndex {
  577. return [Int](nextIndex...lastIndex)
  578. } else {
  579. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  580. }
  581. }
  582. }
  583. }
  584. class SafeArray<Element> {
  585. private var array: Array<Element> = []
  586. private let lock = NSLock()
  587. subscript(index: Int) -> Element? {
  588. get {
  589. lock.lock()
  590. defer { lock.unlock() }
  591. return array.indices ~= index ? array[index] : nil
  592. }
  593. set {
  594. lock.lock()
  595. defer { lock.unlock() }
  596. if let newValue = newValue, array.indices ~= index {
  597. array[index] = newValue
  598. }
  599. }
  600. }
  601. var count : Int {
  602. lock.lock()
  603. defer { lock.unlock() }
  604. return array.count
  605. }
  606. func reserveCapacity(_ count: Int) {
  607. lock.lock()
  608. defer { lock.unlock() }
  609. array.reserveCapacity(count)
  610. }
  611. func append(_ element: Element) {
  612. lock.lock()
  613. defer { lock.unlock() }
  614. array += [element]
  615. }
  616. func removeAll() {
  617. lock.lock()
  618. defer { lock.unlock() }
  619. array = []
  620. }
  621. }
  622. #endif
  623. #endif