AnimatedImageView.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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) 2014-2016 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. /// `AnimatedImageView` is a subclass of `UIImageView` for displaying animated image.
  36. public class AnimatedImageView: UIImageView {
  37. /// Proxy object for prevending a reference cycle between the CADDisplayLink and AnimatedImageView.
  38. class TargetProxy {
  39. private weak var target: AnimatedImageView?
  40. init(target: AnimatedImageView) {
  41. self.target = target
  42. }
  43. @objc func onScreenUpdate() {
  44. target?.updateFrame()
  45. }
  46. }
  47. // MARK: - Public property
  48. /// Whether automatically play the animation when the view become visible. Default is true.
  49. public var autoPlayAnimatedImage = true
  50. /// The size of the frame cache.
  51. public var framePreloadCount = 10
  52. /// Specifies whether the GIF frames should be pre-scaled to save memory. Default is true.
  53. public var needsPrescaling = true
  54. /// The animation timer's run loop mode. Default is `NSRunLoopCommonModes`. Set this property to `NSDefaultRunLoopMode` will make the animation pause during UIScrollView scrolling.
  55. public var runLoopMode = NSRunLoopCommonModes {
  56. willSet {
  57. if runLoopMode == newValue {
  58. return
  59. } else {
  60. stopAnimating()
  61. displayLink.removeFromRunLoop(NSRunLoop.mainRunLoop(), forMode: runLoopMode)
  62. displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: newValue)
  63. startAnimating()
  64. }
  65. }
  66. }
  67. // MARK: - Private property
  68. /// `Animator` instance that holds the frames of a specific image in memory.
  69. private var animator: Animator?
  70. /// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy. :D
  71. private var displayLinkInitialized: Bool = false
  72. /// A display link that keeps calling the `updateFrame` method on every screen refresh.
  73. private lazy var displayLink: CADisplayLink = {
  74. self.displayLinkInitialized = true
  75. let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
  76. displayLink.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: self.runLoopMode)
  77. displayLink.paused = true
  78. return displayLink
  79. }()
  80. // MARK: - Override
  81. override public var image: Image? {
  82. didSet {
  83. if image != oldValue {
  84. reset()
  85. }
  86. setNeedsDisplay()
  87. layer.setNeedsDisplay()
  88. }
  89. }
  90. deinit {
  91. if displayLinkInitialized {
  92. displayLink.invalidate()
  93. }
  94. }
  95. override public func isAnimating() -> Bool {
  96. if displayLinkInitialized {
  97. return !displayLink.paused
  98. } else {
  99. return super.isAnimating()
  100. }
  101. }
  102. /// Starts the animation.
  103. override public func startAnimating() {
  104. if self.isAnimating() {
  105. return
  106. } else {
  107. displayLink.paused = false
  108. }
  109. }
  110. /// Stops the animation.
  111. override public func stopAnimating() {
  112. super.stopAnimating()
  113. if displayLinkInitialized {
  114. displayLink.paused = true
  115. }
  116. }
  117. override public func displayLayer(layer: CALayer) {
  118. if let currentFrame = animator?.currentFrame {
  119. layer.contents = currentFrame.CGImage
  120. } else {
  121. layer.contents = image?.CGImage
  122. }
  123. }
  124. override public func didMoveToWindow() {
  125. super.didMoveToWindow()
  126. didMove()
  127. }
  128. override public func didMoveToSuperview() {
  129. super.didMoveToSuperview()
  130. didMove()
  131. }
  132. // This is for back compatibility that using regular UIImageView to show GIF.
  133. override func shouldPreloadAllGIF() -> Bool {
  134. return false
  135. }
  136. // MARK: - Private method
  137. /// Reset the animator.
  138. private func reset() {
  139. animator = nil
  140. if let imageSource = image?.kf_imageSource?.imageRef {
  141. animator = Animator(imageSource: imageSource, contentMode: contentMode, size: bounds.size, framePreloadCount: framePreloadCount)
  142. animator?.needsPrescaling = needsPrescaling
  143. animator?.prepareFrames()
  144. }
  145. didMove()
  146. }
  147. private func didMove() {
  148. if autoPlayAnimatedImage && animator != nil {
  149. if let _ = superview, _ = window {
  150. startAnimating()
  151. } else {
  152. stopAnimating()
  153. }
  154. }
  155. }
  156. /// Update the current frame with the displayLink duration.
  157. private func updateFrame() {
  158. if animator?.updateCurrentFrame(displayLink.duration) ?? false {
  159. layer.setNeedsDisplay()
  160. }
  161. }
  162. }
  163. /// Keeps a reference to an `Image` instance and its duration as a GIF frame.
  164. struct AnimatedFrame {
  165. var image: Image?
  166. let duration: NSTimeInterval
  167. static func null() -> AnimatedFrame {
  168. return AnimatedFrame(image: .None, duration: 0.0)
  169. }
  170. }
  171. // MARK: - Animator
  172. ///
  173. class Animator {
  174. // MARK: Private property
  175. private let size: CGSize
  176. private let maxFrameCount: Int
  177. private let imageSource: CGImageSourceRef
  178. private var animatedFrames = [AnimatedFrame]()
  179. private let maxTimeStep: NSTimeInterval = 1.0
  180. private var frameCount = 0
  181. private var currentFrameIndex = 0
  182. private var currentPreloadIndex = 0
  183. private var timeSinceLastFrameChange: NSTimeInterval = 0.0
  184. private var needsPrescaling = true
  185. /// Loop count of animatd image.
  186. private var loopCount = 0
  187. var currentFrame: UIImage? {
  188. return frameAtIndex(currentFrameIndex)
  189. }
  190. var contentMode: UIViewContentMode = .ScaleToFill
  191. /**
  192. Init an animator with image source reference.
  193. - parameter imageSource: The reference of animated image.
  194. - parameter contentMode: Content mode of AnimatedImageView.
  195. - parameter size: Size of AnimatedImageView.
  196. - framePreloadCount: Frame cache size.
  197. - returns: The animator object.
  198. */
  199. init(imageSource src: CGImageSourceRef, contentMode mode: UIViewContentMode, size: CGSize, framePreloadCount: Int) {
  200. self.imageSource = src
  201. self.contentMode = mode
  202. self.size = size
  203. self.maxFrameCount = framePreloadCount
  204. }
  205. func frameAtIndex(index: Int) -> Image? {
  206. return animatedFrames[index].image
  207. }
  208. func prepareFrames() {
  209. frameCount = CGImageSourceGetCount(imageSource)
  210. if let properties = CGImageSourceCopyProperties(imageSource, nil),
  211. gifInfo = (properties as NSDictionary)[kCGImagePropertyGIFDictionary as String] as? NSDictionary,
  212. loopCount = gifInfo[kCGImagePropertyGIFLoopCount as String] as? Int {
  213. self.loopCount = loopCount
  214. }
  215. let frameToProcess = min(frameCount, maxFrameCount)
  216. animatedFrames.reserveCapacity(frameToProcess)
  217. animatedFrames = (0..<frameToProcess).reduce([]) { $0 + pure(prepareFrame($1))}
  218. }
  219. func prepareFrame(index: Int) -> AnimatedFrame {
  220. guard let imageRef = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
  221. return AnimatedFrame.null()
  222. }
  223. let frameDuration = imageSource.kf_GIFPropertiesAtIndex(index).flatMap { (gifInfo) -> Double? in
  224. let unclampedDelayTime = gifInfo[kCGImagePropertyGIFUnclampedDelayTime as String] as Double?
  225. let delayTime = gifInfo[kCGImagePropertyGIFDelayTime as String] as Double?
  226. let duration = unclampedDelayTime ?? delayTime
  227. /**
  228. http://opensource.apple.com/source/WebCore/WebCore-7600.1.25/platform/graphics/cg/ImageSourceCG.cpp
  229. Many annoying ads specify a 0 duration to make an image flash as quickly as
  230. possible. We follow Safari and Firefox's behavior and use a duration of 100 ms
  231. for any frames that specify a duration of <= 10 ms.
  232. See <rdar://problem/7689300> and <http://webkit.org/b/36082> for more information.
  233. See also: http://nullsleep.tumblr.com/post/16524517190/animated-gif-minimum-frame-delay-browser.
  234. */
  235. return duration > 0.011 ? duration : 0.100
  236. }
  237. let image = Image(CGImage: imageRef)
  238. let scaledImage: Image?
  239. if needsPrescaling {
  240. scaledImage = image.kf_resizeToSize(size, contentMode: contentMode)
  241. } else {
  242. scaledImage = image
  243. }
  244. return AnimatedFrame(image: scaledImage, duration: frameDuration ?? 0.0)
  245. }
  246. /**
  247. Updates the current frame if necessary using the frame timer and the duration of each frame in `animatedFrames`.
  248. */
  249. func updateCurrentFrame(duration: CFTimeInterval) -> Bool {
  250. timeSinceLastFrameChange += min(maxTimeStep, duration)
  251. guard let frameDuration = animatedFrames[safe: currentFrameIndex]?.duration where frameDuration <= timeSinceLastFrameChange else {
  252. return false
  253. }
  254. timeSinceLastFrameChange -= frameDuration
  255. let lastFrameIndex = currentFrameIndex
  256. currentFrameIndex += 1
  257. currentFrameIndex = currentFrameIndex % animatedFrames.count
  258. if animatedFrames.count < frameCount {
  259. animatedFrames[lastFrameIndex] = prepareFrame(currentPreloadIndex)
  260. currentPreloadIndex += 1
  261. currentPreloadIndex = currentPreloadIndex % frameCount
  262. }
  263. return true
  264. }
  265. }
  266. // MARK: - Resize
  267. extension Image {
  268. func kf_resizeToSize(size: CGSize, contentMode: UIViewContentMode) -> Image {
  269. switch contentMode {
  270. case .ScaleAspectFit:
  271. let newSize = self.size.kf_sizeConstrainedSize(size)
  272. return kf_resizeToSize(newSize)
  273. case .ScaleAspectFill:
  274. let newSize = self.size.kf_sizeFillingSize(size)
  275. return kf_resizeToSize(newSize)
  276. default:
  277. return kf_resizeToSize(size)
  278. }
  279. }
  280. private func kf_resizeToSize(size: CGSize) -> Image {
  281. UIGraphicsBeginImageContextWithOptions(size, false, 0.0)
  282. drawInRect(CGRect(origin: CGPoint.zero, size: size))
  283. let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
  284. UIGraphicsEndImageContext()
  285. return resizedImage ?? self
  286. }
  287. }
  288. extension CGSize {
  289. func kf_sizeConstrainedSize(size: CGSize) -> CGSize {
  290. let aspectWidth = round(kf_aspectRatio * size.height)
  291. let aspectHeight = round(size.width / kf_aspectRatio)
  292. return aspectWidth > size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  293. }
  294. func kf_sizeFillingSize(size: CGSize) -> CGSize {
  295. let aspectWidth = round(kf_aspectRatio * size.height)
  296. let aspectHeight = round(size.width / kf_aspectRatio)
  297. return aspectWidth < size.width ? CGSize(width: size.width, height: aspectHeight) : CGSize(width: aspectWidth, height: size.height)
  298. }
  299. private var kf_aspectRatio: CGFloat {
  300. return height == 0.0 ? 1.0 : width / height
  301. }
  302. }
  303. extension CGImageSourceRef {
  304. func kf_GIFPropertiesAtIndex(index: Int) -> [String: Double]? {
  305. let properties = CGImageSourceCopyPropertiesAtIndex(self, index, nil) as Dictionary?
  306. return properties?[kCGImagePropertyGIFDictionary as String] as? [String: Double]
  307. }
  308. }
  309. extension Array {
  310. subscript(safe index: Int) -> Element? {
  311. return indices ~= index ? self[index] : .None
  312. }
  313. }
  314. func pure<T>(a: T) -> [T] {
  315. return [a]
  316. }