AnimatedImageView.swift 29 KB

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