AnimatedImageView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. /// Represents a subclass of `UIImageView` for displaying animated image.
  53. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
  54. /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
  55. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
  56. /// view to load GIF data, you could give this class a try.
  57. ///
  58. /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
  59. /// it would be fairly easy to switch between them.
  60. open class AnimatedImageView: UIImageView {
  61. /// Proxy object for prevending a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  62. class TargetProxy {
  63. private weak var target: AnimatedImageView?
  64. init(target: AnimatedImageView) {
  65. self.target = target
  66. }
  67. @objc func onScreenUpdate() {
  68. target?.updateFrame()
  69. }
  70. }
  71. /// Enumeration that specifies repeat count of GIF
  72. public enum RepeatCount: Equatable {
  73. case once
  74. case finite(count: UInt)
  75. case infinite
  76. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  77. switch (lhs, rhs) {
  78. case let (.finite(l), .finite(r)):
  79. return l == r
  80. case (.once, .once),
  81. (.infinite, .infinite):
  82. return true
  83. case (.once, .finite(let count)),
  84. (.finite(let count), .once):
  85. return count == 1
  86. case (.once, _),
  87. (.infinite, _),
  88. (.finite, _):
  89. return false
  90. }
  91. }
  92. }
  93. // MARK: - Public property
  94. /// Whether automatically play the animation when the view become visible. Default is `true`.
  95. public var autoPlayAnimatedImage = true
  96. /// The count of the frames should be preloaded before shown.
  97. public var framePreloadCount = 10
  98. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  99. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
  100. /// Default is `true`.
  101. public var needsPrescaling = true
  102. /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
  103. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  104. public var runLoopMode = RunLoop.Mode.common {
  105. willSet {
  106. guard runLoopMode == newValue else { return }
  107. stopAnimating()
  108. displayLink.remove(from: .main, forMode: runLoopMode)
  109. displayLink.add(to: .main, forMode: newValue)
  110. startAnimating()
  111. }
  112. }
  113. /// The repeat count. The animated image will keep animate until it the loop count reaches this value.
  114. /// Setting this value to another one will reset current animation.
  115. ///
  116. /// Default is `.infinite`, which means the aniamtion will last forever.
  117. public var repeatCount = RepeatCount.infinite {
  118. didSet {
  119. if oldValue != repeatCount {
  120. reset()
  121. setNeedsDisplay()
  122. layer.setNeedsDisplay()
  123. }
  124. }
  125. }
  126. /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
  127. public weak var delegate: AnimatedImageViewDelegate?
  128. // MARK: - Private property
  129. /// `Animator` instance that holds the frames of a specific image in memory.
  130. private var animator: Animator?
  131. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  132. private var isDisplayLinkInitialized: Bool = false
  133. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  134. private lazy var displayLink: CADisplayLink = {
  135. isDisplayLinkInitialized = true
  136. let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  137. displayLink.add(to: .main, forMode: runLoopMode)
  138. displayLink.isPaused = true
  139. return displayLink
  140. }()
  141. // MARK: - Override
  142. override open var image: Image? {
  143. didSet {
  144. if image != oldValue {
  145. reset()
  146. }
  147. setNeedsDisplay()
  148. layer.setNeedsDisplay()
  149. }
  150. }
  151. deinit {
  152. if isDisplayLinkInitialized {
  153. displayLink.invalidate()
  154. }
  155. }
  156. override open var isAnimating: Bool {
  157. if isDisplayLinkInitialized {
  158. return !displayLink.isPaused
  159. } else {
  160. return super.isAnimating
  161. }
  162. }
  163. /// Starts the animation.
  164. override open func startAnimating() {
  165. guard !isAnimating else { return }
  166. if animator?.isReachMaxRepeatCount ?? false {
  167. return
  168. }
  169. displayLink.isPaused = false
  170. }
  171. /// Stops the animation.
  172. override open func stopAnimating() {
  173. super.stopAnimating()
  174. if isDisplayLinkInitialized {
  175. displayLink.isPaused = true
  176. }
  177. }
  178. override open func display(_ layer: CALayer) {
  179. if let currentFrame = animator?.currentFrame {
  180. layer.contents = currentFrame.cgImage
  181. } else {
  182. layer.contents = image?.cgImage
  183. }
  184. }
  185. override open func didMoveToWindow() {
  186. super.didMoveToWindow()
  187. didMove()
  188. }
  189. override open func didMoveToSuperview() {
  190. super.didMoveToSuperview()
  191. didMove()
  192. }
  193. // This is for back compatibility that using regular `UIImageView` to show animated image.
  194. override func shouldPreloadAllAnimation() -> Bool {
  195. return false
  196. }
  197. // Reset the animator.
  198. private func reset() {
  199. animator = nil
  200. if let imageSource = image?.kf.imageSource {
  201. let animator = Animator(
  202. imageSource: imageSource,
  203. contentMode: contentMode,
  204. size: bounds.size,
  205. framePreloadCount: framePreloadCount,
  206. repeatCount: repeatCount)
  207. animator.delegate = self
  208. animator.needsPrescaling = needsPrescaling
  209. animator.prepareFramesAsynchronously()
  210. self.animator = animator
  211. }
  212. didMove()
  213. }
  214. private func didMove() {
  215. if autoPlayAnimatedImage && animator != nil {
  216. if let _ = superview, let _ = window {
  217. startAnimating()
  218. } else {
  219. stopAnimating()
  220. }
  221. }
  222. }
  223. /// Update the current frame with the displayLink duration.
  224. private func updateFrame() {
  225. let duration: CFTimeInterval
  226. // CA based display link is opt-out from ProMotion by default.
  227. // So the duration and its FPS might not match.
  228. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  229. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  230. // cause the preferredFramesPerSecond being 0
  231. if displayLink.preferredFramesPerSecond == 0 {
  232. duration = displayLink.duration
  233. } else {
  234. // Some devices (like iPad Pro 10.5) will have a different FPS.
  235. duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
  236. }
  237. if animator?.updateCurrentFrame(duration: duration) ?? false {
  238. layer.setNeedsDisplay()
  239. if animator?.isReachMaxRepeatCount ?? false {
  240. stopAnimating()
  241. delegate?.animatedImageViewDidFinishAnimating(self)
  242. }
  243. }
  244. }
  245. }
  246. extension AnimatedImageView: AnimatorDelegate {
  247. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  248. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  249. }
  250. }
  251. /// Keeps a reference to an `Image` instance and its duration as a GIF frame.
  252. struct AnimatedFrame {
  253. var image: Image?
  254. let duration: TimeInterval
  255. static let null = AnimatedFrame(image: .none, duration: 0.0)
  256. }
  257. protocol AnimatorDelegate: AnyObject {
  258. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt)
  259. }
  260. // MARK: - Animator
  261. class Animator {
  262. // MARK: Private property
  263. private let size: CGSize
  264. private let maxFrameCount: Int
  265. private let imageSource: CGImageSource
  266. private let maxRepeatCount: AnimatedImageView.RepeatCount
  267. private var animatedFrames = [AnimatedFrame]()
  268. private let maxTimeStep: TimeInterval = 1.0
  269. private var frameCount = 0
  270. private var currentFrameIndex = 0
  271. private var currentFrameIndexInBuffer = 0
  272. private var currentPreloadIndex = 0
  273. private var timeSinceLastFrameChange: TimeInterval = 0.0
  274. private var currentRepeatCount: UInt = 0
  275. var needsPrescaling = true
  276. weak var delegate: AnimatorDelegate?
  277. /// Loop count of animated image.
  278. private var loopCount = 0
  279. var currentFrame: UIImage? {
  280. return frame(at: currentFrameIndexInBuffer)
  281. }
  282. var isReachMaxRepeatCount: Bool {
  283. switch maxRepeatCount {
  284. case .once:
  285. return currentRepeatCount >= 1
  286. case .finite(let maxCount):
  287. return currentRepeatCount >= maxCount
  288. case .infinite:
  289. return false
  290. }
  291. }
  292. var contentMode = UIView.ContentMode.scaleToFill
  293. private lazy var preloadQueue: DispatchQueue = {
  294. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  295. }()
  296. /// Creates an animator with image source reference.
  297. ///
  298. /// - Parameters:
  299. /// - source: The reference of animated image.
  300. /// - mode: Content mode of the `AnimatedImageView`.
  301. /// - size: Size of the `AnimatedImageView`.
  302. /// - count: Count of frames needed to be preloaded.
  303. /// - repeatCount: The repeat count should this animator uses.
  304. init(imageSource source: CGImageSource,
  305. contentMode mode: UIView.ContentMode,
  306. size: CGSize,
  307. framePreloadCount count: Int,
  308. repeatCount: AnimatedImageView.RepeatCount) {
  309. self.imageSource = source
  310. self.contentMode = mode
  311. self.size = size
  312. self.maxFrameCount = count
  313. self.maxRepeatCount = repeatCount
  314. }
  315. func frame(at index: Int) -> Image? {
  316. return animatedFrames[safe: index]?.image
  317. }
  318. func prepareFramesAsynchronously() {
  319. preloadQueue.async { [weak self] in
  320. self?.prepareFrames()
  321. }
  322. }
  323. private func prepareFrames() {
  324. frameCount = CGImageSourceGetCount(imageSource)
  325. if let properties = CGImageSourceCopyProperties(imageSource, nil),
  326. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  327. let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
  328. {
  329. self.loopCount = loopCount
  330. }
  331. let frameToProcess = min(frameCount, maxFrameCount)
  332. animatedFrames.reserveCapacity(frameToProcess)
  333. animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
  334. currentPreloadIndex = (frameToProcess + 1) % frameCount - 1
  335. }
  336. private func prepareFrame(at index: Int) -> AnimatedFrame {
  337. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
  338. return .null
  339. }
  340. let defaultGIFFrameDuration = 0.100
  341. let frameDuration = imageSource.kf.gifProperties(at: index).map {
  342. gifInfo -> Double in
  343. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
  344. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
  345. let duration = unclampedDelayTime ?? delayTime ?? 0.0
  346. /*
  347. http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
  348. Many annoying ads specify a 0 duration to make an image flash as quickly as
  349. possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
  350. for any frames that specify a duration of <= 10 ms.
  351. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
  352. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
  353. */
  354. return duration > 0.011 ? duration : defaultGIFFrameDuration
  355. } ?? defaultGIFFrameDuration
  356. let image = Image(cgImage: imageRef)
  357. let scaledImage: Image?
  358. if needsPrescaling {
  359. scaledImage = image.kf.resize(to: size, for: contentMode)
  360. } else {
  361. scaledImage = image
  362. }
  363. return AnimatedFrame(image: scaledImage, duration: frameDuration)
  364. }
  365. /// Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
  366. func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
  367. timeSinceLastFrameChange += min(maxTimeStep, duration)
  368. guard let frameDuration = animatedFrames[safe: currentFrameIndexInBuffer]?.duration, frameDuration <= timeSinceLastFrameChange else {
  369. return false
  370. }
  371. timeSinceLastFrameChange -= frameDuration
  372. let lastFrameIndex = currentFrameIndexInBuffer
  373. currentFrameIndexInBuffer += 1
  374. currentFrameIndexInBuffer = currentFrameIndexInBuffer % animatedFrames.count
  375. if animatedFrames.count < frameCount {
  376. preloadFrameAsynchronously(at: lastFrameIndex)
  377. }
  378. currentFrameIndex += 1
  379. if currentFrameIndex == frameCount {
  380. currentFrameIndex = 0
  381. currentRepeatCount += 1
  382. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  383. }
  384. return true
  385. }
  386. private func preloadFrameAsynchronously(at index: Int) {
  387. preloadQueue.async { [weak self] in
  388. self?.preloadFrame(at: index)
  389. }
  390. }
  391. private func preloadFrame(at index: Int) {
  392. animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
  393. currentPreloadIndex += 1
  394. currentPreloadIndex = currentPreloadIndex % frameCount
  395. }
  396. }
  397. extension CGImageSource: KingfisherClassCompatible { }
  398. extension KingfisherClass where Base: CGImageSource {
  399. func gifProperties(at index: Int) -> [String: Double]? {
  400. let properties = CGImageSourceCopyPropertiesAtIndex(base, index, nil) as Dictionary?
  401. return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
  402. }
  403. }
  404. extension Array {
  405. subscript(safe index: Int) -> Element? {
  406. return indices ~= index ? self[index] : nil
  407. }
  408. }
  409. private func pure<T>(_ value: T) -> [T] {
  410. return [value]
  411. }