123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657 |
- #if !os(watchOS)
- #if canImport(UIKit)
- import UIKit
- import ImageIO
- public protocol AnimatedImageViewDelegate: AnyObject {
-
-
-
-
-
- func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
-
-
-
- func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
- }
- extension AnimatedImageViewDelegate {
- public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
- public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
- }
- let KFRunLoopModeCommon = RunLoop.Mode.common
- open class AnimatedImageView: UIImageView {
-
-
- class TargetProxy {
- private weak var target: AnimatedImageView?
-
- init(target: AnimatedImageView) {
- self.target = target
- }
-
- @objc func onScreenUpdate() {
- target?.updateFrameIfNeeded()
- }
- }
-
- public enum RepeatCount: Equatable {
- case once
- case finite(count: UInt)
- case infinite
- public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
- switch (lhs, rhs) {
- case let (.finite(l), .finite(r)):
- return l == r
- case (.once, .once),
- (.infinite, .infinite):
- return true
- case (.once, .finite(let count)),
- (.finite(let count), .once):
- return count == 1
- case (.once, _),
- (.infinite, _),
- (.finite, _):
- return false
- }
- }
- }
-
-
-
- public var autoPlayAnimatedImage = true
-
-
- public var framePreloadCount = 10
-
-
-
-
- public var needsPrescaling = true
-
-
- public var backgroundDecode = true
-
-
- public var runLoopMode = KFRunLoopModeCommon {
- willSet {
- guard runLoopMode != newValue else { return }
- stopAnimating()
- displayLink.remove(from: .main, forMode: runLoopMode)
- displayLink.add(to: .main, forMode: newValue)
- startAnimating()
- }
- }
-
-
-
-
-
- public var repeatCount = RepeatCount.infinite {
- didSet {
- if oldValue != repeatCount {
- reset()
- setNeedsDisplay()
- layer.setNeedsDisplay()
- }
- }
- }
-
- public weak var delegate: AnimatedImageViewDelegate?
-
- public private(set) var animator: Animator?
-
-
- private lazy var preloadQueue: DispatchQueue = {
- return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
- }()
-
-
- private var isDisplayLinkInitialized: Bool = false
-
-
- private lazy var displayLink: CADisplayLink = {
- isDisplayLinkInitialized = true
- let displayLink = CADisplayLink(target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
- displayLink.add(to: .main, forMode: runLoopMode)
- displayLink.isPaused = true
- return displayLink
- }()
-
-
- override open var image: KFCrossPlatformImage? {
- didSet {
- if image != oldValue {
- reset()
- }
- setNeedsDisplay()
- layer.setNeedsDisplay()
- }
- }
-
- open override var isHighlighted: Bool {
- get {
- super.isHighlighted
- }
- set {
-
-
- if displayLink.isPaused {
- super.isHighlighted = newValue
- }
- }
- }
-
- deinit {
- if isDisplayLinkInitialized {
- displayLink.invalidate()
- }
- }
-
- override open var isAnimating: Bool {
- if isDisplayLinkInitialized {
- return !displayLink.isPaused
- } else {
- return super.isAnimating
- }
- }
-
-
- override open func startAnimating() {
- guard !isAnimating else { return }
- guard let animator = animator else { return }
- guard !animator.isReachMaxRepeatCount else { return }
- displayLink.isPaused = false
- }
-
-
- override open func stopAnimating() {
- super.stopAnimating()
- if isDisplayLinkInitialized {
- displayLink.isPaused = true
- }
- }
-
- override open func display(_ layer: CALayer) {
- if let currentFrame = animator?.currentFrameImage {
- layer.contents = currentFrame.cgImage
- } else {
- layer.contents = image?.cgImage
- }
- }
-
- override open func didMoveToWindow() {
- super.didMoveToWindow()
- didMove()
- }
-
- override open func didMoveToSuperview() {
- super.didMoveToSuperview()
- didMove()
- }
-
- override func shouldPreloadAllAnimation() -> Bool {
- return false
- }
-
- private func reset() {
- animator = nil
- if let image = image, let imageSource = image.kf.imageSource {
- let targetSize = bounds.scaled(UIScreen.main.scale).size
- let animator = Animator(
- imageSource: imageSource,
- contentMode: contentMode,
- size: targetSize,
- imageSize: image.kf.size,
- imageScale: image.kf.scale,
- framePreloadCount: framePreloadCount,
- repeatCount: repeatCount,
- preloadQueue: preloadQueue)
- animator.delegate = self
- animator.needsPrescaling = needsPrescaling
- animator.backgroundDecode = backgroundDecode
- animator.prepareFramesAsynchronously()
- self.animator = animator
- }
- didMove()
- }
-
- private func didMove() {
- if autoPlayAnimatedImage && animator != nil {
- if let _ = superview, let _ = window {
- startAnimating()
- } else {
- stopAnimating()
- }
- }
- }
-
-
- private func updateFrameIfNeeded() {
- guard let animator = animator else {
- return
- }
- guard !animator.isFinished else {
- stopAnimating()
- delegate?.animatedImageViewDidFinishAnimating(self)
- return
- }
- let duration: CFTimeInterval
-
-
-
-
-
- let preferredFramesPerSecond = displayLink.preferredFramesPerSecond
- if preferredFramesPerSecond == 0 {
- duration = displayLink.duration
- } else {
-
- duration = 1.0 / TimeInterval(preferredFramesPerSecond)
- }
- animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
- if hasNewFrame {
- self?.layer.setNeedsDisplay()
- }
- }
- }
- }
- protocol AnimatorDelegate: AnyObject {
- func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
- }
- extension AnimatedImageView: AnimatorDelegate {
- func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
- delegate?.animatedImageView(self, didPlayAnimationLoops: count)
- }
- }
- extension AnimatedImageView {
-
- struct AnimatedFrame {
-
- let image: UIImage?
-
- let duration: TimeInterval
-
-
- var placeholderFrame: AnimatedFrame {
- return AnimatedFrame(image: nil, duration: duration)
- }
-
- var isPlaceholder: Bool {
- return image == nil
- }
-
-
-
-
- func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
- return AnimatedFrame(image: image, duration: duration)
- }
- }
- }
- extension AnimatedImageView {
-
-
- public class Animator {
- private let size: CGSize
- private let imageSize: CGSize
- private let imageScale: CGFloat
-
- public let maxFrameCount: Int
- private let imageSource: CGImageSource
- private let maxRepeatCount: RepeatCount
- private let maxTimeStep: TimeInterval = 1.0
- private let animatedFrames = SafeArray<AnimatedFrame>()
- private var frameCount = 0
- private var timeSinceLastFrameChange: TimeInterval = 0.0
- private var currentRepeatCount: UInt = 0
- var isFinished: Bool = false
- var needsPrescaling = true
- var backgroundDecode = true
- weak var delegate: AnimatorDelegate?
-
- var loopDuration: TimeInterval = 0
-
- public var currentFrameImage: UIImage? {
- return frame(at: currentFrameIndex)
- }
-
- public var currentFrameDuration: TimeInterval {
- return duration(at: currentFrameIndex)
- }
-
- public internal(set) var currentFrameIndex = 0 {
- didSet {
- previousFrameIndex = oldValue
- }
- }
- var previousFrameIndex = 0 {
- didSet {
- preloadQueue.async {
- self.updatePreloadedFrames()
- }
- }
- }
- var isReachMaxRepeatCount: Bool {
- switch maxRepeatCount {
- case .once:
- return currentRepeatCount >= 1
- case .finite(let maxCount):
- return currentRepeatCount >= maxCount
- case .infinite:
- return false
- }
- }
-
- public var isLastFrame: Bool {
- return currentFrameIndex == frameCount - 1
- }
- var preloadingIsNeeded: Bool {
- return maxFrameCount < frameCount - 1
- }
- var contentMode = UIView.ContentMode.scaleToFill
- private lazy var preloadQueue: DispatchQueue = {
- return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
- }()
-
-
-
-
-
-
-
-
-
-
-
- init(imageSource source: CGImageSource,
- contentMode mode: UIView.ContentMode,
- size: CGSize,
- imageSize: CGSize,
- imageScale: CGFloat,
- framePreloadCount count: Int,
- repeatCount: RepeatCount,
- preloadQueue: DispatchQueue) {
- self.imageSource = source
- self.contentMode = mode
- self.size = size
- self.imageSize = imageSize
- self.imageScale = imageScale
- self.maxFrameCount = count
- self.maxRepeatCount = repeatCount
- self.preloadQueue = preloadQueue
-
- GraphicsContext.begin(size: imageSize, scale: imageScale)
- }
-
- deinit {
- GraphicsContext.end()
- }
-
-
-
- public func frame(at index: Int) -> KFCrossPlatformImage? {
- return animatedFrames[index]?.image
- }
- public func duration(at index: Int) -> TimeInterval {
- return animatedFrames[index]?.duration ?? .infinity
- }
- func prepareFramesAsynchronously() {
- frameCount = Int(CGImageSourceGetCount(imageSource))
- animatedFrames.reserveCapacity(frameCount)
- preloadQueue.async { [weak self] in
- self?.setupAnimatedFrames()
- }
- }
- func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
- incrementTimeSinceLastFrameChange(with: duration)
- if currentFrameDuration > timeSinceLastFrameChange {
- handler(false)
- } else {
- resetTimeSinceLastFrameChange()
- incrementCurrentFrameIndex()
- handler(true)
- }
- }
- private func setupAnimatedFrames() {
- resetAnimatedFrames()
- var duration: TimeInterval = 0
- (0..<frameCount).forEach { index in
- let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
- duration += min(frameDuration, maxTimeStep)
- animatedFrames.append(AnimatedFrame(image: nil, duration: frameDuration))
- if index > maxFrameCount { return }
- animatedFrames[index] = animatedFrames[index]?.makeAnimatedFrame(image: loadFrame(at: index))
- }
- self.loopDuration = duration
- }
- private func resetAnimatedFrames() {
- animatedFrames.removeAll()
- }
- private func loadFrame(at index: Int) -> UIImage? {
- let resize = needsPrescaling && size != .zero
- let options: [CFString: Any]?
- if resize {
- options = [
- kCGImageSourceCreateThumbnailFromImageIfAbsent: true,
- kCGImageSourceCreateThumbnailWithTransform: true,
- kCGImageSourceShouldCacheImmediately: true,
- kCGImageSourceThumbnailMaxPixelSize: max(size.width, size.height)
- ]
- } else {
- options = nil
- }
- guard let cgImage = CGImageSourceCreateImageAtIndex(imageSource, index, options as CFDictionary?) else {
- return nil
- }
- let image = KFCrossPlatformImage(cgImage: cgImage)
-
- guard let context = GraphicsContext.current(size: imageSize, scale: imageScale, inverting: true, cgImage: cgImage) else {
- return image
- }
-
- return backgroundDecode ? image.kf.decoded(on: context) : image
- }
-
- private func updatePreloadedFrames() {
- guard preloadingIsNeeded else {
- return
- }
- animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex]?.placeholderFrame
- preloadIndexes(start: currentFrameIndex).forEach { index in
- guard let currentAnimatedFrame = animatedFrames[index] else { return }
- if !currentAnimatedFrame.isPlaceholder { return }
- animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
- }
- }
- private func incrementCurrentFrameIndex() {
- currentFrameIndex = increment(frameIndex: currentFrameIndex)
- if isLastFrame {
- currentRepeatCount += 1
- if isReachMaxRepeatCount {
- isFinished = true
- }
- delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
- }
- }
- private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
- timeSinceLastFrameChange += min(maxTimeStep, duration)
- }
- private func resetTimeSinceLastFrameChange() {
- timeSinceLastFrameChange -= currentFrameDuration
- }
- private func increment(frameIndex: Int, by value: Int = 1) -> Int {
- return (frameIndex + value) % frameCount
- }
- private func preloadIndexes(start index: Int) -> [Int] {
- let nextIndex = increment(frameIndex: index)
- let lastIndex = increment(frameIndex: index, by: maxFrameCount)
- if lastIndex >= nextIndex {
- return [Int](nextIndex...lastIndex)
- } else {
- return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
- }
- }
- }
- }
- class SafeArray<Element> {
- private var array: Array<Element> = []
- private let lock = NSLock()
-
- subscript(index: Int) -> Element? {
- get {
- lock.lock()
- defer { lock.unlock() }
- return array.indices ~= index ? array[index] : nil
- }
-
- set {
- lock.lock()
- defer { lock.unlock() }
- if let newValue = newValue, array.indices ~= index {
- array[index] = newValue
- }
- }
- }
-
- var count : Int {
- lock.lock()
- defer { lock.unlock() }
- return array.count
- }
-
- func reserveCapacity(_ count: Int) {
- lock.lock()
- defer { lock.unlock() }
- array.reserveCapacity(count)
- }
-
- func append(_ element: Element) {
- lock.lock()
- defer { lock.unlock() }
- array += [element]
- }
-
- func removeAll() {
- lock.lock()
- defer { lock.unlock() }
- array = []
- }
- }
- #endif
- #endif
|