AnimatedImageView.swift 30 KB

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