AnimatedImageView.swift 20 KB

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