AnimatedImageView.swift 26 KB

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