AnimatedImageView.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 prevending 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?.updateFrame()
  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 aniamtion 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. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  137. private var isDisplayLinkInitialized: Bool = false
  138. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  139. private lazy var displayLink: CADisplayLink = {
  140. isDisplayLinkInitialized = true
  141. let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  142. displayLink.add(to: .main, forMode: runLoopMode)
  143. displayLink.isPaused = true
  144. return displayLink
  145. }()
  146. // MARK: - Override
  147. override open var image: Image? {
  148. didSet {
  149. if image != oldValue {
  150. reset()
  151. }
  152. setNeedsDisplay()
  153. layer.setNeedsDisplay()
  154. }
  155. }
  156. deinit {
  157. if isDisplayLinkInitialized {
  158. displayLink.invalidate()
  159. }
  160. }
  161. override open var isAnimating: Bool {
  162. if isDisplayLinkInitialized {
  163. return !displayLink.isPaused
  164. } else {
  165. return super.isAnimating
  166. }
  167. }
  168. /// Starts the animation.
  169. override open func startAnimating() {
  170. guard !isAnimating else { return }
  171. if animator?.isReachMaxRepeatCount ?? false {
  172. return
  173. }
  174. displayLink.isPaused = false
  175. }
  176. /// Stops the animation.
  177. override open func stopAnimating() {
  178. super.stopAnimating()
  179. if isDisplayLinkInitialized {
  180. displayLink.isPaused = true
  181. }
  182. }
  183. override open func display(_ layer: CALayer) {
  184. if let currentFrame = animator?.currentFrame {
  185. layer.contents = currentFrame.cgImage
  186. } else {
  187. layer.contents = image?.cgImage
  188. }
  189. }
  190. override open func didMoveToWindow() {
  191. super.didMoveToWindow()
  192. didMove()
  193. }
  194. override open func didMoveToSuperview() {
  195. super.didMoveToSuperview()
  196. didMove()
  197. }
  198. // This is for back compatibility that using regular `UIImageView` to show animated image.
  199. override func shouldPreloadAllAnimation() -> Bool {
  200. return false
  201. }
  202. // Reset the animator.
  203. private func reset() {
  204. animator = nil
  205. if let imageSource = image?.kf.imageSource {
  206. let animator = Animator(
  207. imageSource: imageSource,
  208. contentMode: contentMode,
  209. size: bounds.size,
  210. framePreloadCount: framePreloadCount,
  211. repeatCount: repeatCount)
  212. animator.delegate = self
  213. animator.needsPrescaling = needsPrescaling
  214. animator.prepareFramesAsynchronously()
  215. self.animator = animator
  216. }
  217. didMove()
  218. }
  219. private func didMove() {
  220. if autoPlayAnimatedImage && animator != nil {
  221. if let _ = superview, let _ = window {
  222. startAnimating()
  223. } else {
  224. stopAnimating()
  225. }
  226. }
  227. }
  228. /// Update the current frame with the displayLink duration.
  229. private func updateFrame() {
  230. let duration: CFTimeInterval
  231. // CA based display link is opt-out from ProMotion by default.
  232. // So the duration and its FPS might not match.
  233. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  234. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  235. // cause the preferredFramesPerSecond being 0
  236. if displayLink.preferredFramesPerSecond == 0 {
  237. duration = displayLink.duration
  238. } else {
  239. // Some devices (like iPad Pro 10.5) will have a different FPS.
  240. duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
  241. }
  242. if animator?.updateCurrentFrame(duration: duration) ?? false {
  243. layer.setNeedsDisplay()
  244. if animator?.isReachMaxRepeatCount ?? false {
  245. stopAnimating()
  246. delegate?.animatedImageViewDidFinishAnimating(self)
  247. }
  248. }
  249. }
  250. }
  251. extension AnimatedImageView: AnimatorDelegate {
  252. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  253. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  254. }
  255. }
  256. /// Keeps a reference to an `Image` instance and its duration as a GIF frame.
  257. struct AnimatedFrame {
  258. var image: Image?
  259. let duration: TimeInterval
  260. static let null = AnimatedFrame(image: .none, duration: 0.0)
  261. }
  262. protocol AnimatorDelegate: AnyObject {
  263. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt)
  264. }
  265. // MARK: - Animator
  266. class Animator {
  267. // MARK: Private property
  268. private let size: CGSize
  269. private let maxFrameCount: Int
  270. private let imageSource: CGImageSource
  271. private let maxRepeatCount: AnimatedImageView.RepeatCount
  272. private var animatedFrames = [AnimatedFrame]()
  273. private let maxTimeStep: TimeInterval = 1.0
  274. private var frameCount = 0
  275. private var currentFrameIndex = 0
  276. private var currentFrameIndexInBuffer = 0
  277. private var currentPreloadIndex = 0
  278. private var timeSinceLastFrameChange: TimeInterval = 0.0
  279. private var currentRepeatCount: UInt = 0
  280. var needsPrescaling = true
  281. weak var delegate: AnimatorDelegate?
  282. /// Loop count of animated image.
  283. private var loopCount = 0
  284. var currentFrame: UIImage? {
  285. return frame(at: currentFrameIndexInBuffer)
  286. }
  287. var isReachMaxRepeatCount: Bool {
  288. switch maxRepeatCount {
  289. case .once:
  290. return currentRepeatCount >= 1
  291. case .finite(let maxCount):
  292. return currentRepeatCount >= maxCount
  293. case .infinite:
  294. return false
  295. }
  296. }
  297. var contentMode = UIView.ContentMode.scaleToFill
  298. private lazy var preloadQueue: DispatchQueue = {
  299. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  300. }()
  301. /// Creates an animator with image source reference.
  302. ///
  303. /// - Parameters:
  304. /// - source: The reference of animated image.
  305. /// - mode: Content mode of the `AnimatedImageView`.
  306. /// - size: Size of the `AnimatedImageView`.
  307. /// - count: Count of frames needed to be preloaded.
  308. /// - repeatCount: The repeat count should this animator uses.
  309. init(imageSource source: CGImageSource,
  310. contentMode mode: UIView.ContentMode,
  311. size: CGSize,
  312. framePreloadCount count: Int,
  313. repeatCount: AnimatedImageView.RepeatCount) {
  314. self.imageSource = source
  315. self.contentMode = mode
  316. self.size = size
  317. self.maxFrameCount = count
  318. self.maxRepeatCount = repeatCount
  319. }
  320. func frame(at index: Int) -> Image? {
  321. return animatedFrames[safe: index]?.image
  322. }
  323. func prepareFramesAsynchronously() {
  324. preloadQueue.async { [weak self] in
  325. self?.prepareFrames()
  326. }
  327. }
  328. private func prepareFrames() {
  329. frameCount = CGImageSourceGetCount(imageSource)
  330. if let properties = CGImageSourceCopyProperties(imageSource, nil),
  331. let gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  332. let loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int
  333. {
  334. self.loopCount = loopCount
  335. }
  336. let frameToProcess = min(frameCount, maxFrameCount)
  337. animatedFrames.reserveCapacity(frameToProcess)
  338. animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame(at: $1))}
  339. currentPreloadIndex = (frameToProcess + 1) % frameCount - 1
  340. }
  341. private func prepareFrame(at index: Int) -> AnimatedFrame {
  342. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
  343. return .null
  344. }
  345. let defaultGIFFrameDuration = 0.100
  346. let frameDuration = imageSource.gifProperties(at: index).map {
  347. gifInfo -> Double in
  348. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
  349. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
  350. let duration = unclampedDelayTime ?? delayTime ?? 0.0
  351. /*
  352. http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
  353. Many annoying ads specify a 0 duration to make an image flash as quickly as
  354. possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
  355. for any frames that specify a duration of <= 10 ms.
  356. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
  357. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
  358. */
  359. return duration > 0.011 ? duration : defaultGIFFrameDuration
  360. } ?? defaultGIFFrameDuration
  361. let image = Image(cgImage: imageRef)
  362. let scaledImage: Image?
  363. if needsPrescaling {
  364. scaledImage = image.kf.resize(to: size, for: contentMode)
  365. } else {
  366. scaledImage = image
  367. }
  368. return AnimatedFrame(image: scaledImage, duration: frameDuration)
  369. }
  370. /// Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
  371. func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
  372. timeSinceLastFrameChange += min(maxTimeStep, duration)
  373. guard let frameDuration = animatedFrames[safe: currentFrameIndexInBuffer]?.duration, frameDuration <= timeSinceLastFrameChange else {
  374. return false
  375. }
  376. timeSinceLastFrameChange -= frameDuration
  377. let lastFrameIndex = currentFrameIndexInBuffer
  378. currentFrameIndexInBuffer += 1
  379. currentFrameIndexInBuffer = currentFrameIndexInBuffer % animatedFrames.count
  380. if animatedFrames.count < frameCount {
  381. preloadFrameAsynchronously(at: lastFrameIndex)
  382. }
  383. currentFrameIndex += 1
  384. if currentFrameIndex == frameCount {
  385. currentFrameIndex = 0
  386. currentRepeatCount += 1
  387. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  388. }
  389. return true
  390. }
  391. private func preloadFrameAsynchronously(at index: Int) {
  392. preloadQueue.async { [weak self] in
  393. self?.preloadFrame(at: index)
  394. }
  395. }
  396. private func preloadFrame(at index: Int) {
  397. animatedFrames[index] = prepareFrame(at: currentPreloadIndex)
  398. currentPreloadIndex += 1
  399. currentPreloadIndex = currentPreloadIndex % frameCount
  400. }
  401. }
  402. extension CGImageSource {
  403. func gifProperties(at index: Int) -> [String: Double]? {
  404. let properties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary?
  405. return properties?[kCGImagePropertyGIFDictionary] as? [String: Double]
  406. }
  407. }
  408. extension Array {
  409. subscript(safe index: Int) -> Element? {
  410. return indices ~= index ? self[index] : nil
  411. }
  412. }
  413. private func pure<T>(_ value: T) -> [T] {
  414. return [value]
  415. }