You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

615 lines
21 KiB

  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. #if !os(watchOS)
  34. #if canImport(UIKit)
  35. import UIKit
  36. import ImageIO
  37. /// Protocol of `AnimatedImageView`.
  38. public protocol AnimatedImageViewDelegate: AnyObject {
  39. /// Called after the animatedImageView has finished each animation loop.
  40. ///
  41. /// - Parameters:
  42. /// - imageView: The `AnimatedImageView` that is being animated.
  43. /// - count: The looped count.
  44. func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
  45. /// Called after the `AnimatedImageView` has reached the max repeat count.
  46. ///
  47. /// - Parameter imageView: The `AnimatedImageView` that is being animated.
  48. func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
  49. }
  50. extension AnimatedImageViewDelegate {
  51. public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
  52. public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
  53. }
  54. #if swift(>=4.2)
  55. let KFRunLoopModeCommon = RunLoop.Mode.common
  56. #else
  57. let KFRunLoopModeCommon = RunLoopMode.commonModes
  58. #endif
  59. /// Represents a subclass of `UIImageView` for displaying animated image.
  60. /// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
  61. /// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
  62. /// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
  63. /// view to load GIF data, you could give this class a try.
  64. ///
  65. /// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
  66. /// it would be fairly easy to switch between them.
  67. open class AnimatedImageView: UIImageView {
  68. /// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
  69. class TargetProxy {
  70. private weak var target: AnimatedImageView?
  71. init(target: AnimatedImageView) {
  72. self.target = target
  73. }
  74. @objc func onScreenUpdate() {
  75. target?.updateFrameIfNeeded()
  76. }
  77. }
  78. /// Enumeration that specifies repeat count of GIF
  79. public enum RepeatCount: Equatable {
  80. case once
  81. case finite(count: UInt)
  82. case infinite
  83. public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
  84. switch (lhs, rhs) {
  85. case let (.finite(l), .finite(r)):
  86. return l == r
  87. case (.once, .once),
  88. (.infinite, .infinite):
  89. return true
  90. case (.once, .finite(let count)),
  91. (.finite(let count), .once):
  92. return count == 1
  93. case (.once, _),
  94. (.infinite, _),
  95. (.finite, _):
  96. return false
  97. }
  98. }
  99. }
  100. // MARK: - Public property
  101. /// Whether automatically play the animation when the view become visible. Default is `true`.
  102. public var autoPlayAnimatedImage = true
  103. /// The count of the frames should be preloaded before shown.
  104. public var framePreloadCount = 10
  105. /// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
  106. /// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
  107. /// Default is `true`.
  108. public var needsPrescaling = true
  109. /// Decode the GIF frames in background thread before using. It will decode frames data and do a off-screen
  110. /// rendering to extract pixel information in background. This can reduce the main thread CPU usage.
  111. public var backgroundDecode = true
  112. /// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
  113. /// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
  114. public var runLoopMode = KFRunLoopModeCommon {
  115. willSet {
  116. guard runLoopMode != newValue else { return }
  117. stopAnimating()
  118. displayLink.remove(from: .main, forMode: runLoopMode)
  119. displayLink.add(to: .main, forMode: newValue)
  120. startAnimating()
  121. }
  122. }
  123. /// The repeat count. The animated image will keep animate until it the loop count reaches this value.
  124. /// Setting this value to another one will reset current animation.
  125. ///
  126. /// Default is `.infinite`, which means the animation will last forever.
  127. public var repeatCount = RepeatCount.infinite {
  128. didSet {
  129. if oldValue != repeatCount {
  130. reset()
  131. setNeedsDisplay()
  132. layer.setNeedsDisplay()
  133. }
  134. }
  135. }
  136. /// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
  137. public weak var delegate: AnimatedImageViewDelegate?
  138. // MARK: - Private property
  139. /// `Animator` instance that holds the frames of a specific image in memory.
  140. private var animator: Animator?
  141. // Dispatch queue used for preloading images.
  142. private lazy var preloadQueue: DispatchQueue = {
  143. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  144. }()
  145. // A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
  146. private var isDisplayLinkInitialized: Bool = false
  147. // A display link that keeps calling the `updateFrame` method on every screen refresh.
  148. private lazy var displayLink: CADisplayLink = {
  149. isDisplayLinkInitialized = true
  150. let displayLink = CADisplayLink(
  151. target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  152. displayLink.add(to: .main, forMode: runLoopMode)
  153. displayLink.isPaused = true
  154. return displayLink
  155. }()
  156. // MARK: - Override
  157. override open var image: KFCrossPlatformImage? {
  158. didSet {
  159. if image != oldValue {
  160. reset()
  161. }
  162. setNeedsDisplay()
  163. layer.setNeedsDisplay()
  164. }
  165. }
  166. deinit {
  167. if isDisplayLinkInitialized {
  168. displayLink.invalidate()
  169. }
  170. }
  171. override open var isAnimating: Bool {
  172. if isDisplayLinkInitialized {
  173. return !displayLink.isPaused
  174. } else {
  175. return super.isAnimating
  176. }
  177. }
  178. /// Starts the animation.
  179. override open func startAnimating() {
  180. guard !isAnimating else { return }
  181. if animator?.isReachMaxRepeatCount ?? false {
  182. return
  183. }
  184. displayLink.isPaused = false
  185. }
  186. /// Stops the animation.
  187. override open func stopAnimating() {
  188. super.stopAnimating()
  189. if isDisplayLinkInitialized {
  190. displayLink.isPaused = true
  191. }
  192. }
  193. override open func display(_ layer: CALayer) {
  194. if let currentFrame = animator?.currentFrameImage {
  195. layer.contents = currentFrame.cgImage
  196. } else {
  197. layer.contents = image?.cgImage
  198. }
  199. }
  200. override open func didMoveToWindow() {
  201. super.didMoveToWindow()
  202. didMove()
  203. }
  204. override open func didMoveToSuperview() {
  205. super.didMoveToSuperview()
  206. didMove()
  207. }
  208. // This is for back compatibility that using regular `UIImageView` to show animated image.
  209. override func shouldPreloadAllAnimation() -> Bool {
  210. return false
  211. }
  212. // Reset the animator.
  213. private func reset() {
  214. animator = nil
  215. if let imageSource = image?.kf.imageSource {
  216. let targetSize = bounds.scaled(UIScreen.main.scale).size
  217. let animator = Animator(
  218. imageSource: imageSource,
  219. contentMode: contentMode,
  220. size: targetSize,
  221. framePreloadCount: framePreloadCount,
  222. repeatCount: repeatCount,
  223. preloadQueue: preloadQueue)
  224. animator.delegate = self
  225. animator.needsPrescaling = needsPrescaling
  226. animator.backgroundDecode = backgroundDecode
  227. animator.prepareFramesAsynchronously()
  228. self.animator = animator
  229. }
  230. didMove()
  231. }
  232. private func didMove() {
  233. if autoPlayAnimatedImage && animator != nil {
  234. if let _ = superview, let _ = window {
  235. startAnimating()
  236. } else {
  237. stopAnimating()
  238. }
  239. }
  240. }
  241. /// Update the current frame with the displayLink duration.
  242. private func updateFrameIfNeeded() {
  243. guard let animator = animator else {
  244. return
  245. }
  246. guard !animator.isFinished else {
  247. stopAnimating()
  248. delegate?.animatedImageViewDidFinishAnimating(self)
  249. return
  250. }
  251. let duration: CFTimeInterval
  252. // CA based display link is opt-out from ProMotion by default.
  253. // So the duration and its FPS might not match.
  254. // See [#718](https://github.com/onevcat/Kingfisher/issues/718)
  255. // By setting CADisableMinimumFrameDuration to YES in Info.plist may
  256. // cause the preferredFramesPerSecond being 0
  257. let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
  258. if preferredFramesPerSecond == 0 {
  259. duration = displayLink.duration
  260. } else {
  261. // Some devices (like iPad Pro 10.5) will have a different FPS.
  262. duration = 1.0 / TimeInterval(preferredFramesPerSecond)
  263. }
  264. animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
  265. if hasNewFrame {
  266. self?.layer.setNeedsDisplay()
  267. }
  268. }
  269. }
  270. }
  271. protocol AnimatorDelegate: AnyObject {
  272. func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
  273. }
  274. extension AnimatedImageView: AnimatorDelegate {
  275. func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
  276. delegate?.animatedImageView(self, didPlayAnimationLoops: count)
  277. }
  278. }
  279. extension AnimatedImageView {
  280. // Represents a single frame in a GIF.
  281. struct AnimatedFrame {
  282. // The image to display for this frame. Its value is nil when the frame is removed from the buffer.
  283. let image: UIImage?
  284. // The duration that this frame should remain active.
  285. let duration: TimeInterval
  286. // A placeholder frame with no image assigned.
  287. // Used to replace frames that are no longer needed in the animation.
  288. var placeholderFrame: AnimatedFrame {
  289. return AnimatedFrame(image: nil, duration: duration)
  290. }
  291. // Whether this frame instance contains an image or not.
  292. var isPlaceholder: Bool {
  293. return image == nil
  294. }
  295. // Returns a new instance from an optional image.
  296. //
  297. // - parameter image: An optional `UIImage` instance to be assigned to the new frame.
  298. // - returns: An `AnimatedFrame` instance.
  299. func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
  300. return AnimatedFrame(image: image, duration: duration)
  301. }
  302. }
  303. }
  304. extension AnimatedImageView {
  305. // MARK: - Animator
  306. class Animator {
  307. private let size: CGSize
  308. private let maxFrameCount: Int
  309. private let imageSource: CGImageSource
  310. private let maxRepeatCount: RepeatCount
  311. private let maxTimeStep: TimeInterval = 1.0
  312. private let animatedFrames = SafeArray<AnimatedFrame>()
  313. private var frameCount = 0
  314. private var timeSinceLastFrameChange: TimeInterval = 0.0
  315. private var currentRepeatCount: UInt = 0
  316. var isFinished: Bool = false
  317. var needsPrescaling = true
  318. var backgroundDecode = true
  319. weak var delegate: AnimatorDelegate?
  320. // Total duration of one animation loop
  321. var loopDuration: TimeInterval = 0
  322. // Current active frame image
  323. var currentFrameImage: UIImage? {
  324. return frame(at: currentFrameIndex)
  325. }
  326. // Current active frame duration
  327. var currentFrameDuration: TimeInterval {
  328. return duration(at: currentFrameIndex)
  329. }
  330. // The index of the current GIF frame.
  331. var currentFrameIndex = 0 {
  332. didSet {
  333. previousFrameIndex = oldValue
  334. }
  335. }
  336. var previousFrameIndex = 0 {
  337. didSet {
  338. preloadQueue.async {
  339. self.updatePreloadedFrames()
  340. }
  341. }
  342. }
  343. var isReachMaxRepeatCount: Bool {
  344. switch maxRepeatCount {
  345. case .once:
  346. return currentRepeatCount >= 1
  347. case .finite(let maxCount):
  348. return currentRepeatCount >= maxCount
  349. case .infinite:
  350. return false
  351. }
  352. }
  353. var isLastFrame: Bool {
  354. return currentFrameIndex == frameCount - 1
  355. }
  356. var preloadingIsNeeded: Bool {
  357. return maxFrameCount < frameCount - 1
  358. }
  359. var contentMode = UIView.ContentMode.scaleToFill
  360. private lazy var preloadQueue: DispatchQueue = {
  361. return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
  362. }()
  363. /// Creates an animator with image source reference.
  364. ///
  365. /// - Parameters:
  366. /// - source: The reference of animated image.
  367. /// - mode: Content mode of the `AnimatedImageView`.
  368. /// - size: Size of the `AnimatedImageView`.
  369. /// - count: Count of frames needed to be preloaded.
  370. /// - repeatCount: The repeat count should this animator uses.
  371. init(imageSource source: CGImageSource,
  372. contentMode mode: UIView.ContentMode,
  373. size: CGSize,
  374. framePreloadCount count: Int,
  375. repeatCount: RepeatCount,
  376. preloadQueue: DispatchQueue) {
  377. self.imageSource = source
  378. self.contentMode = mode
  379. self.size = size
  380. self.maxFrameCount = count
  381. self.maxRepeatCount = repeatCount
  382. self.preloadQueue = preloadQueue
  383. }
  384. func frame(at index: Int) -> KFCrossPlatformImage? {
  385. return animatedFrames[index]?.image
  386. }
  387. func duration(at index: Int) -> TimeInterval {
  388. return animatedFrames[index]?.duration ?? .infinity
  389. }
  390. func prepareFramesAsynchronously() {
  391. frameCount = Int(CGImageSourceGetCount(imageSource))
  392. animatedFrames.reserveCapacity(frameCount)
  393. preloadQueue.async { [weak self] in
  394. self?.setupAnimatedFrames()
  395. }
  396. }
  397. func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
  398. incrementTimeSinceLastFrameChange(with: duration)
  399. if currentFrameDuration > timeSinceLastFrameChange {
  400. handler(false)
  401. } else {
  402. resetTimeSinceLastFrameChange()
  403. incrementCurrentFrameIndex()
  404. handler(true)
  405. }
  406. }
  407. private func setupAnimatedFrames() {
  408. resetAnimatedFrames()
  409. var duration: TimeInterval = 0
  410. (0..<frameCount).forEach { index in
  411. let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
  412. duration += min(frameDuration, maxTimeStep)
  413. animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
  414. if index > maxFrameCount { return }
  415. animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
  416. }
  417. self.loopDuration = duration
  418. }
  419. private func resetAnimatedFrames() {
  420. animatedFrames.removeAll()
  421. }
  422. private func loadFrame(at index: Int) -> UIImage? {
  423. let options: [CFString: Any] = [
  424. kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
  425. kCGImageSourceCreateThumbnailWithTransform: true,
  426. kCGImageSourceShouldCacheImmediately: true,
  427. kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
  428. ]
  429. let resize = needsPrescaling && size != .zero
  430. guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource,
  431. index,
  432. resize ? options as CFDictionary : nil) else {
  433. return nil
  434. }
  435. let image = KFCrossPlatformImage(cgImage: cgImage)
  436. return backgroundDecode ? image.kf.decoded : image
  437. }
  438. private func updatePreloadedFrames() {
  439. guard preloadingIsNeeded else {
  440. return
  441. }
  442. animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame
  443. preloadIndexes(start: currentFrameIndex).forEach { index in
  444. guard let currentAnimatedFrame = animatedFrames[index] else { return }
  445. if !currentAnimatedFrame.isPlaceholder { return }
  446. animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
  447. }
  448. }
  449. private func incrementCurrentFrameIndex() {
  450. currentFrameIndex = increment(frameIndex: currentFrameIndex)
  451. if isLastFrame {
  452. currentRepeatCount += 1
  453. if isReachMaxRepeatCount {
  454. isFinished = true
  455. }
  456. delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
  457. }
  458. }
  459. private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
  460. timeSinceLastFrameChange += min(maxTimeStep, duration)
  461. }
  462. private func resetTimeSinceLastFrameChange() {
  463. timeSinceLastFrameChange -= currentFrameDuration
  464. }
  465. private func increment(frameIndex: Int, by value: Int = 1) -> Int {
  466. return (frameIndex + value) % frameCount
  467. }
  468. private func preloadIndexes(start index: Int) -> [Int] {
  469. let nextIndex = increment(frameIndex: index)
  470. let lastIndex = increment(frameIndex: index, by: maxFrameCount)
  471. if lastIndex >= nextIndex {
  472. return [Int](nextIndex...lastIndex)
  473. } else {
  474. return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
  475. }
  476. }
  477. }
  478. }
  479. class SafeArray<Element> {
  480. private var array: Array<Element> = []
  481. private let lock = NSLock()
  482. subscript(index: Int) -> Element? {
  483. get {
  484. lock.lock()
  485. defer { lock.unlock() }
  486. return array.indices ~= index ? array[index] : nil
  487. }
  488. set {
  489. lock.lock()
  490. defer { lock.unlock() }
  491. if let newValue = newValue, array.indices ~= index {
  492. array[index] = newValue
  493. }
  494. }
  495. }
  496. var count : Int {
  497. lock.lock()
  498. defer { lock.unlock() }
  499. return array.count
  500. }
  501. func reserveCapacity(_ count: Int) {
  502. lock.lock()
  503. defer { lock.unlock() }
  504. array.reserveCapacity(count)
  505. }
  506. func append(_ element: Element) {
  507. lock.lock()
  508. defer { lock.unlock() }
  509. array += [element]
  510. }
  511. func removeAll() {
  512. lock.lock()
  513. defer { lock.unlock() }
  514. array = []
  515. }
  516. }
  517. #endif
  518. #endif