AnimatedImageView.swift 19 KB

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