AnimatedImageView.swift 19 KB

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