AnimatedImageView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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. 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(
  146. target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  147. displayLink.add(to: .main, forMode: runLoopMode)
  148. displayLink.isPaused = true
  149. return displayLink
  150. }()
  151. // MARK: - Override
  152. override open var image: Image? {
  153. didSet {
  154. if image != oldValue {
  155. reset()
  156. }
  157. setNeedsDisplay()
  158. layer.setNeedsDisplay()
  159. }
  160. }
  161. deinit {
  162. if isDisplayLinkInitialized {
  163. displayLink.invalidate()
  164. }
  165. }
  166. override open var isAnimating: Bool {
  167. if isDisplayLinkInitialized {
  168. return !displayLink.isPaused
  169. } else {
  170. return super.isAnimating
  171. }
  172. }
  173. /// Starts the animation.
  174. override open func startAnimating() {
  175. guard !isAnimating else { return }
  176. if animator?.isReachMaxRepeatCount ?? false {
  177. return
  178. }
  179. displayLink.isPaused = false
  180. }
  181. /// Stops the animation.
  182. override open func stopAnimating() {
  183. super.stopAnimating()
  184. if isDisplayLinkInitialized {
  185. displayLink.isPaused = true
  186. }
  187. }
  188. override open func display(_ layer: CALayer) {
  189. if let currentFrame = animator?.currentFrameImage {
  190. layer.contents = currentFrame.cgImage
  191. } else {
  192. layer.contents = image?.cgImage
  193. }
  194. }
  195. override open func didMoveToWindow() {
  196. super.didMoveToWindow()
  197. didMove()
  198. }
  199. override open func didMoveToSuperview() {
  200. super.didMoveToSuperview()
  201. didMove()
  202. }
  203. // This is for back compatibility that using regular `UIImageView` to show animated image.
  204. override func shouldPreloadAllAnimation() -> Bool {
  205. return false
  206. }
  207. // Reset the animator.
  208. private func reset() {
  209. animator = nil
  210. if let imageSource = image?.kf.imageSource {
  211. let animator = Animator(
  212. imageSource: imageSource,
  213. contentMode: contentMode,
  214. size: bounds.size,
  215. framePreloadCount: framePreloadCount,
  216. repeatCount: repeatCount,
  217. preloadQueue: preloadQueue)
  218. animator.delegate = self
  219. animator.needsPrescaling = needsPrescaling
  220. animator.prepareFramesAsynchronously()
  221. self.animator = animator
  222. }
  223. didMove()
  224. }
  225. private func didMove() {
  226. if autoPlayAnimatedImage && animator != nil {
  227. if let _ = superview, let _ = window {
  228. startAnimating()
  229. } else {
  230. stopAnimating()
  231. }
  232. }
  233. }
  234. /// Update the current frame with the displayLink duration.
  235. private func updateFrameIfNeeded() {
  236. guard let animator = animator else {
  237. return
  238. }
  239. guard !animator.isFinished else {
  240. stopAnimating()
  241. delegate?.animatedImageViewDidFinishAnimating(self)
  242. return
  243. }
  244. let duration: CFTimeInterval
  245. // CA based display link is opt-out from ProMotion by default.
  246. // So the duration and its FPS might not match.
  247. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  248. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  249. // cause the preferredFramesPerSecond being 0
  250. if displayLink.preferredFramesPerSecond == 0 {
  251. duration = displayLink.duration
  252. } else {
  253. // Some devices (like iPad Pro 10.5) will have a different FPS.
  254. duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
  255. }
  256. animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
  257. if hasNewFrame {
  258. self?.layer.setNeedsDisplay()
  259. }
  260. }
  261. }
  262. }
  263. protocol AnimatorDelegate: AnyObject {
  264. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  265. }
  266. extension AnimatedImageView: AnimatorDelegate {
  267. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  268. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  269. }
  270. }
  271. extension AnimatedImageView {
  272. // Represents a single frame in a GIF.
  273. struct AnimatedFrame {
  274. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  275. let image: UIImage?
  276. // The duration that this frame should remain active.
  277. let duration: TimeInterval
  278. // A placeholder frame with no image assigned.
  279. // Used to replace frames that are no longer needed in the animation.
  280. var placeholderFrame: AnimatedFrame {
  281. return AnimatedFrame(image: nil, duration: duration)
  282. }
  283. // Whether this frame instance contains an image or not.
  284. var isPlaceholder: Bool {
  285. return image == nil
  286. }
  287. // Returns a new instance from an optional image.
  288. //
  289. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  290. // - returns: An `AnimatedFrame` instance.
  291. func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
  292. return AnimatedFrame(image: image, duration: duration)
  293. }
  294. }
  295. }
  296. extension AnimatedImageView {
  297. // MARK: - Animator
  298. class Animator {
  299. private let size: CGSize
  300. private let maxFrameCount: Int
  301. private let imageSource: CGImageSource
  302. private let maxRepeatCount: RepeatCount
  303. private let maxTimeStep: TimeInterval = 1.0
  304. private var animatedFrames = [AnimatedFrame]()
  305. private var frameCount = 0
  306. private var timeSinceLastFrameChange: TimeInterval = 0.0
  307. private var currentRepeatCount: UInt = 0
  308. var isFinished: Bool = false
  309. var needsPrescaling = true
  310. weak var delegate: AnimatorDelegate?
  311. // Total duration of one animation loop
  312. var loopDuration: TimeInterval = 0
  313. // Current active frame image
  314. var currentFrameImage: UIImage? {
  315. return frame(at: currentFrameIndex)
  316. }
  317. // Current active frame duration
  318. var currentFrameDuration: TimeInterval {
  319. return duration(at: currentFrameIndex)
  320. }
  321. // The index of the current GIF frame.
  322. var currentFrameIndex = 0 {
  323. didSet {
  324. previousFrameIndex = oldValue
  325. }
  326. }
  327. var previousFrameIndex = 0 {
  328. didSet {
  329. preloadQueue.async {
  330. self.updatePreloadedFrames()
  331. }
  332. }
  333. }
  334. var isReachMaxRepeatCount: Bool {
  335. switch maxRepeatCount {
  336. case .once:
  337. return currentRepeatCount >= 1
  338. case .finite(let maxCount):
  339. return currentRepeatCount >= maxCount
  340. case .infinite:
  341. return false
  342. }
  343. }
  344. var isLastFrame: Bool {
  345. return currentFrameIndex == frameCount - 1
  346. }
  347. var preloadingIsNeeded: Bool {
  348. return maxFrameCount < frameCount - 1
  349. }
  350. var contentMode = UIView.ContentMode.scaleToFill
  351. private lazy var preloadQueue: DispatchQueue = {
  352. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  353. }()
  354. /// Creates an animator with image source reference.
  355. ///
  356. /// - Parameters:
  357. /// - source: The reference of animated image.
  358. /// - mode: Content mode of the `AnimatedImageView`.
  359. /// - size: Size of the `AnimatedImageView`.
  360. /// - count: Count of frames needed to be preloaded.
  361. /// - repeatCount: The repeat count should this animator uses.
  362. init(imageSource source: CGImageSource,
  363. contentMode mode: UIView.ContentMode,
  364. size: CGSize,
  365. framePreloadCount count: Int,
  366. repeatCount: RepeatCount,
  367. preloadQueue: DispatchQueue) {
  368. self.imageSource = source
  369. self.contentMode = mode
  370. self.size = size
  371. self.maxFrameCount = count
  372. self.maxRepeatCount = repeatCount
  373. self.preloadQueue = preloadQueue
  374. }
  375. func frame(at index: Int) -> Image? {
  376. return animatedFrames[safe: index]?.image
  377. }
  378. func duration(at index: Int) -> TimeInterval {
  379. return animatedFrames[safe: index]?.duration ?? .infinity
  380. }
  381. func prepareFramesAsynchronously() {
  382. frameCount = Int(CGImageSourceGetCount(imageSource))
  383. animatedFrames.reserveCapacity(frameCount)
  384. preloadQueue.async { [weak self] in
  385. self?.setupAnimatedFrames()
  386. }
  387. }
  388. func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
  389. incrementTimeSinceLastFrameChange(with: duration)
  390. if currentFrameDuration > timeSinceLastFrameChange {
  391. handler(false)
  392. } else {
  393. resetTimeSinceLastFrameChange()
  394. incrementCurrentFrameIndex()
  395. handler(true)
  396. }
  397. }
  398. private func setupAnimatedFrames() {
  399. resetAnimatedFrames()
  400. var duration: TimeInterval = 0
  401. (0..<frameCount).forEach { index in
  402. let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
  403. duration += min(frameDuration, maxTimeStep)
  404. animatedFrames += [AnimatedFrame(image: nil, duration: frameDuration)]
  405. if index > maxFrameCount { return }
  406. animatedFrames[index] = animatedFrames[index].makeAnimatedFrame(image: loadFrame(at: index))
  407. }
  408. self.loopDuration = duration
  409. }
  410. private func resetAnimatedFrames() {
  411. animatedFrames = []
  412. }
  413. private func loadFrame(at index: Int) -> UIImage? {
  414. guard let image = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
  415. return nil
  416. }
  417. let scaledImage: CGImage
  418. if needsPrescaling, size != .zero {
  419. scaledImage = image.kf.resize(to: size, for: contentMode)
  420. } else {
  421. scaledImage = image
  422. }
  423. return Image(cgImage: scaledImage)
  424. }
  425. private func updatePreloadedFrames() {
  426. guard preloadingIsNeeded else {
  427. return
  428. }
  429. animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex].placeholderFrame
  430. preloadIndexes(start: currentFrameIndex).forEach { index in
  431. let currentAnimatedFrame = animatedFrames[index]
  432. if !currentAnimatedFrame.isPlaceholder { return }
  433. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  434. }
  435. }
  436. private func incrementCurrentFrameIndex() {
  437. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  438. if isReachMaxRepeatCount && isLastFrame {
  439. isFinished = true
  440. } else if currentFrameIndex == 0 {
  441. currentRepeatCount += 1
  442. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  443. }
  444. }
  445. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  446. timeSinceLastFrameChange += min(maxTimeStep, duration)
  447. }
  448. private func resetTimeSinceLastFrameChange() {
  449. timeSinceLastFrameChange -= currentFrameDuration
  450. }
  451. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  452. return (frameIndex + value) % frameCount
  453. }
  454. private func preloadIndexes(start index: Int) -> [Int] {
  455. let nextIndex = increment(frameIndex: index)
  456. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  457. if lastIndex >= nextIndex {
  458. return [Int](nextIndex...lastIndex)
  459. } else {
  460. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  461. }
  462. }
  463. }
  464. }
  465. extension Array {
  466. subscript(safe index: Int) -> Element? {
  467. return indices ~= index ? self[index] : nil
  468. }
  469. }