AnimatedImageView.swift 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. #if swift(>=4.2)
  55. let KFRunLoopModeCommon = RunLoop.Mode.common
  56. #else
  57. let KFRunLoopModeCommon = RunLoopMode.commonModes
  58. #endif
  59. /// Represents a subclass of `UIImageView` for displaying animated image.
  60. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
  61. /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
  62. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
  63. /// view to load GIF data, you could give this class a try.
  64. ///
  65. /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
  66. /// it would be fairly easy to switch between them.
  67. open class AnimatedImageView: UIImageView {
  68. /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  69. class TargetProxy {
  70. private weak var target: AnimatedImageView?
  71. init(target: AnimatedImageView) {
  72. self.target = target
  73. }
  74. @objc func onScreenUpdate() {
  75. target?.updateFrameIfNeeded()
  76. }
  77. }
  78. /// Enumeration that specifies repeat count of GIF
  79. public enum RepeatCount: Equatable {
  80. case once
  81. case finite(count: UInt)
  82. case infinite
  83. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  84. switch (lhs, rhs) {
  85. case let (.finite(l), .finite(r)):
  86. return l == r
  87. case (.once, .once),
  88. (.infinite, .infinite):
  89. return true
  90. case (.once, .finite(let count)),
  91. (.finite(let count), .once):
  92. return count == 1
  93. case (.once, _),
  94. (.infinite, _),
  95. (.finite, _):
  96. return false
  97. }
  98. }
  99. }
  100. // MARK: - Public property
  101. /// Whether automatically play the animation when the view become visible. Default is `true`.
  102. public var autoPlayAnimatedImage = true
  103. /// The count of the frames should be preloaded before shown.
  104. public var framePreloadCount = 10
  105. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  106. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
  107. /// Default is `true`.
  108. public var needsPrescaling = true
  109. /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
  110. /// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
  111. public var backgroundDecode = true
  112. /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
  113. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  114. public var runLoopMode = KFRunLoopModeCommon {
  115. willSet {
  116. guard runLoopMode != newValue else { return }
  117. stopAnimating()
  118. displayLink.remove(from: .main, forMode: runLoopMode)
  119. displayLink.add(to: .main, forMode: newValue)
  120. startAnimating()
  121. }
  122. }
  123. /// The repeat count. The animated image will keep animate until it the loop count reaches this value.
  124. /// Setting this value to another one will reset current animation.
  125. ///
  126. /// Default is `.infinite`, which means the animation will last forever.
  127. public var repeatCount = RepeatCount.infinite {
  128. didSet {
  129. if oldValue != repeatCount {
  130. reset()
  131. setNeedsDisplay()
  132. layer.setNeedsDisplay()
  133. }
  134. }
  135. }
  136. /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
  137. public weak var delegate: AnimatedImageViewDelegate?
  138. /// The `Animator` instance that holds the frames of a specific image in memory.
  139. public private(set) var animator: Animator?
  140. // MARK: - Private property
  141. // Dispatch queue used for preloading images.
  142. private lazy var preloadQueue: DispatchQueue = {
  143. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  144. }()
  145. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  146. private var isDisplayLinkInitialized: Bool = false
  147. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  148. private lazy var displayLink: CADisplayLink = {
  149. isDisplayLinkInitialized = true
  150. let displayLink = CADisplayLink(
  151. target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  152. displayLink.add(to: .main, forMode: runLoopMode)
  153. displayLink.isPaused = true
  154. return displayLink
  155. }()
  156. // MARK: - Override
  157. override open var image: KFCrossPlatformImage? {
  158. didSet {
  159. if image != oldValue {
  160. reset()
  161. }
  162. setNeedsDisplay()
  163. layer.setNeedsDisplay()
  164. }
  165. }
  166. open override var isHighlighted: Bool {
  167. get {
  168. super.isHighlighted
  169. }
  170. set {
  171. // Highlighted image is unsupported for animated images.
  172. // See https://github.com/onevcat/Kingfisher/issues/1679
  173. if displayLink.isPaused {
  174. super.isHighlighted = newValue
  175. }
  176. }
  177. }
  178. deinit {
  179. if isDisplayLinkInitialized {
  180. displayLink.invalidate()
  181. }
  182. }
  183. override open var isAnimating: Bool {
  184. if isDisplayLinkInitialized {
  185. return !displayLink.isPaused
  186. } else {
  187. return super.isAnimating
  188. }
  189. }
  190. /// Starts the animation.
  191. override open func startAnimating() {
  192. guard !isAnimating else { return }
  193. guard let animator = animator else { return }
  194. guard !animator.isReachMaxRepeatCount else { return }
  195. displayLink.isPaused = false
  196. }
  197. /// Stops the animation.
  198. override open func stopAnimating() {
  199. super.stopAnimating()
  200. if isDisplayLinkInitialized {
  201. displayLink.isPaused = true
  202. }
  203. }
  204. override open func display(_ layer: CALayer) {
  205. if let currentFrame = animator?.currentFrameImage {
  206. layer.contents = currentFrame.cgImage
  207. } else {
  208. layer.contents = image?.cgImage
  209. }
  210. }
  211. override open func didMoveToWindow() {
  212. super.didMoveToWindow()
  213. didMove()
  214. }
  215. override open func didMoveToSuperview() {
  216. super.didMoveToSuperview()
  217. didMove()
  218. }
  219. // This is for back compatibility that using regular `UIImageView` to show animated image.
  220. override func shouldPreloadAllAnimation() -> Bool {
  221. return false
  222. }
  223. // Reset the animator.
  224. private func reset() {
  225. animator = nil
  226. if let imageSource = image?.kf.imageSource {
  227. let targetSize = bounds.scaled(UIScreen.main.scale).size
  228. let animator = Animator(
  229. imageSource: imageSource,
  230. contentMode: contentMode,
  231. size: targetSize,
  232. framePreloadCount: framePreloadCount,
  233. repeatCount: repeatCount,
  234. preloadQueue: preloadQueue)
  235. animator.delegate = self
  236. animator.needsPrescaling = needsPrescaling
  237. animator.backgroundDecode = backgroundDecode
  238. animator.prepareFramesAsynchronously()
  239. self.animator = animator
  240. }
  241. didMove()
  242. }
  243. private func didMove() {
  244. if autoPlayAnimatedImage && animator != nil {
  245. if let _ = superview, let _ = window {
  246. startAnimating()
  247. } else {
  248. stopAnimating()
  249. }
  250. }
  251. }
  252. /// Update the current frame with the displayLink duration.
  253. private func updateFrameIfNeeded() {
  254. guard let animator = animator else {
  255. return
  256. }
  257. guard !animator.isFinished else {
  258. stopAnimating()
  259. delegate?.animatedImageViewDidFinishAnimating(self)
  260. return
  261. }
  262. let duration: CFTimeInterval
  263. // CA based display link is opt-out from ProMotion by default.
  264. // So the duration and its FPS might not match.
  265. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  266. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  267. // cause the preferredFramesPerSecond being 0
  268. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  269. if preferredFramesPerSecond == 0 {
  270. duration = displayLink.duration
  271. } else {
  272. // Some devices (like iPad Pro 10.5) will have a different FPS.
  273. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  274. }
  275. animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
  276. if hasNewFrame {
  277. self?.layer.setNeedsDisplay()
  278. }
  279. }
  280. }
  281. }
  282. protocol AnimatorDelegate: AnyObject {
  283. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  284. }
  285. extension AnimatedImageView: AnimatorDelegate {
  286. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  287. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  288. }
  289. }
  290. extension AnimatedImageView {
  291. // Represents a single frame in a GIF.
  292. struct AnimatedFrame {
  293. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  294. let image: UIImage?
  295. // The duration that this frame should remain active.
  296. let duration: TimeInterval
  297. // A placeholder frame with no image assigned.
  298. // Used to replace frames that are no longer needed in the animation.
  299. var placeholderFrame: AnimatedFrame {
  300. return AnimatedFrame(image: nil, duration: duration)
  301. }
  302. // Whether this frame instance contains an image or not.
  303. var isPlaceholder: Bool {
  304. return image == nil
  305. }
  306. // Returns a new instance from an optional image.
  307. //
  308. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  309. // - returns: An `AnimatedFrame` instance.
  310. func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
  311. return AnimatedFrame(image: image, duration: duration)
  312. }
  313. }
  314. }
  315. extension AnimatedImageView {
  316. // MARK: - Animator
  317. /// An animator which used to drive the data behind `AnimatedImageView`.
  318. public class Animator {
  319. private let size: CGSize
  320. /// The maximum count of image frames that needs preload.
  321. public let maxFrameCount: Int
  322. private let imageSource: CGImageSource
  323. private let maxRepeatCount: RepeatCount
  324. private let maxTimeStep: TimeInterval = 1.0
  325. private let animatedFrames = SafeArray<AnimatedFrame>()
  326. private var frameCount = 0
  327. private var timeSinceLastFrameChange: TimeInterval = 0.0
  328. private var currentRepeatCount: UInt = 0
  329. var isFinished: Bool = false
  330. var needsPrescaling = true
  331. var backgroundDecode = true
  332. weak var delegate: AnimatorDelegate?
  333. // Total duration of one animation loop
  334. var loopDuration: TimeInterval = 0
  335. /// The image of the current frame.
  336. public var currentFrameImage: UIImage? {
  337. return frame(at: currentFrameIndex)
  338. }
  339. /// The duration of the current active frame duration.
  340. public var currentFrameDuration: TimeInterval {
  341. return duration(at: currentFrameIndex)
  342. }
  343. /// The index of the current animation frame.
  344. public internal(set) var currentFrameIndex = 0 {
  345. didSet {
  346. previousFrameIndex = oldValue
  347. }
  348. }
  349. var previousFrameIndex = 0 {
  350. didSet {
  351. preloadQueue.async {
  352. self.updatePreloadedFrames()
  353. }
  354. }
  355. }
  356. var isReachMaxRepeatCount: Bool {
  357. switch maxRepeatCount {
  358. case .once:
  359. return currentRepeatCount >= 1
  360. case .finite(let maxCount):
  361. return currentRepeatCount >= maxCount
  362. case .infinite:
  363. return false
  364. }
  365. }
  366. /// Whether the current frame is the last frame or not in the animation sequence.
  367. public var isLastFrame: Bool {
  368. return currentFrameIndex == frameCount - 1
  369. }
  370. var preloadingIsNeeded: Bool {
  371. return maxFrameCount < frameCount - 1
  372. }
  373. var contentMode = UIView.ContentMode.scaleToFill
  374. private lazy var preloadQueue: DispatchQueue = {
  375. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  376. }()
  377. /// Creates an animator with image source reference.
  378. ///
  379. /// - Parameters:
  380. /// - source: The reference of animated image.
  381. /// - mode: Content mode of the `AnimatedImageView`.
  382. /// - size: Size of the `AnimatedImageView`.
  383. /// - count: Count of frames needed to be preloaded.
  384. /// - repeatCount: The repeat count should this animator uses.
  385. init(imageSource source: CGImageSource,
  386. contentMode mode: UIView.ContentMode,
  387. size: CGSize,
  388. framePreloadCount count: Int,
  389. repeatCount: RepeatCount,
  390. preloadQueue: DispatchQueue) {
  391. self.imageSource = source
  392. self.contentMode = mode
  393. self.size = size
  394. self.maxFrameCount = count
  395. self.maxRepeatCount = repeatCount
  396. self.preloadQueue = preloadQueue
  397. }
  398. /// Gets the image frame of a given index.
  399. /// - Parameter index: The index of desired image.
  400. /// - Returns: The decoded image at the frame. `nil` if the index is out of bound or the image is not yet loaded.
  401. public func frame(at index: Int) -> KFCrossPlatformImage? {
  402. return animatedFrames[index]?.image
  403. }
  404. public func duration(at index: Int) -> TimeInterval {
  405. return animatedFrames[index]?.duration ?? .infinity
  406. }
  407. func prepareFramesAsynchronously() {
  408. frameCount = Int(CGImageSourceGetCount(imageSource))
  409. animatedFrames.reserveCapacity(frameCount)
  410. preloadQueue.async { [weak self] in
  411. self?.setupAnimatedFrames()
  412. }
  413. }
  414. func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
  415. incrementTimeSinceLastFrameChange(with: duration)
  416. if currentFrameDuration > timeSinceLastFrameChange {
  417. handler(false)
  418. } else {
  419. resetTimeSinceLastFrameChange()
  420. incrementCurrentFrameIndex()
  421. handler(true)
  422. }
  423. }
  424. private func setupAnimatedFrames() {
  425. resetAnimatedFrames()
  426. var duration: TimeInterval = 0
  427. (0..<frameCount).forEach { index in
  428. let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
  429. duration += min(frameDuration, maxTimeStep)
  430. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  431. if index > maxFrameCount { return }
  432. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  433. }
  434. self.loopDuration = duration
  435. }
  436. private func resetAnimatedFrames() {
  437. animatedFrames.removeAll()
  438. }
  439. private func loadFrame(at index: Int) -> UIImage? {
  440. let options: [CFString: Any] = [
  441. kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
  442. kCGImageSourceCreateThumbnailWithTransform: true,
  443. kCGImageSourceShouldCacheImmediately: true,
  444. kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
  445. ]
  446. let resize = needsPrescaling && size != .zero
  447. guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource,
  448. index,
  449. resize ? options as CFDictionary : nil) else {
  450. return nil
  451. }
  452. let image = KFCrossPlatformImage(cgImage: cgImage)
  453. return backgroundDecode ? image.kf.decoded : image
  454. }
  455. private func updatePreloadedFrames() {
  456. guard preloadingIsNeeded else {
  457. return
  458. }
  459. animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame
  460. preloadIndexes(start: currentFrameIndex).forEach { index in
  461. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  462. if !currentAnimatedFrame.isPlaceholder { return }
  463. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  464. }
  465. }
  466. private func incrementCurrentFrameIndex() {
  467. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  468. if isLastFrame {
  469. currentRepeatCount += 1
  470. if isReachMaxRepeatCount {
  471. isFinished = true
  472. }
  473. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  474. }
  475. }
  476. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  477. timeSinceLastFrameChange += min(maxTimeStep, duration)
  478. }
  479. private func resetTimeSinceLastFrameChange() {
  480. timeSinceLastFrameChange -= currentFrameDuration
  481. }
  482. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  483. return (frameIndex + value) % frameCount
  484. }
  485. private func preloadIndexes(start index: Int) -> [Int] {
  486. let nextIndex = increment(frameIndex: index)
  487. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  488. if lastIndex >= nextIndex {
  489. return [Int](nextIndex...lastIndex)
  490. } else {
  491. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  492. }
  493. }
  494. }
  495. }
  496. class SafeArray<Element> {
  497. private var array: Array<Element> = []
  498. private let lock = NSLock()
  499. subscript(index: Int) -> Element? {
  500. get {
  501. lock.lock()
  502. defer { lock.unlock() }
  503. return array.indices ~= index ? array[index] : nil
  504. }
  505. set {
  506. lock.lock()
  507. defer { lock.unlock() }
  508. if let newValue = newValue, array.indices ~= index {
  509. array[index] = newValue
  510. }
  511. }
  512. }
  513. var count : Int {
  514. lock.lock()
  515. defer { lock.unlock() }
  516. return array.count
  517. }
  518. func reserveCapacity(_ count: Int) {
  519. lock.lock()
  520. defer { lock.unlock() }
  521. array.reserveCapacity(count)
  522. }
  523. func append(_ element: Element) {
  524. lock.lock()
  525. defer { lock.unlock() }
  526. array += [element]
  527. }
  528. func removeAll() {
  529. lock.lock()
  530. defer { lock.unlock() }
  531. array = []
  532. }
  533. }
  534. #endif
  535. #endif