AnimatedImageView.swift 17 KB

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