KFImage.swift 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. //
  2. // KFImage.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2019/06/26.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. #if canImport(SwiftUI) && canImport(Combine)
  27. import Combine
  28. import SwiftUI
  29. #if !KingfisherCocoaPods
  30. import Kingfisher
  31. #endif
  32. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  33. extension SwiftUI.Image {
  34. // Creates an SwiftUI.Image with either UIImage or NSImage.
  35. init(crossPlatformImage: KFCrossPlatformImage) {
  36. #if canImport(UIKit)
  37. self.init(uiImage: crossPlatformImage)
  38. #elseif canImport(AppKit)
  39. self.init(nsImage: crossPlatformImage)
  40. #endif
  41. }
  42. }
  43. /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`.
  44. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`.
  45. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  46. public struct KFImage: SwiftUI.View {
  47. /// An image binder that manages loading and cancelling image related task.
  48. @ObservedObject public private(set) var binder: ImageBinder
  49. // Acts as a placeholder when loading an image.
  50. var placeholder: AnyView?
  51. // Whether the download task should be cancelled when the view disappears.
  52. var cancelOnDisappear: Bool = false
  53. // Configurations should be performed on the image.
  54. var configurations: [(SwiftUI.Image) -> SwiftUI.Image]
  55. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  56. /// - Parameter source: The image `Source` defining where to load the target image.
  57. /// - Parameter options: The options should be applied when loading the image.
  58. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  59. public init(source: Source?, options: KingfisherOptionsInfo? = nil) {
  60. binder = ImageBinder(source: source, options: options)
  61. configurations = []
  62. binder.start()
  63. }
  64. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  65. /// - Parameter url: The image URL from where to load the target image.
  66. /// - Parameter options: The options should be applied when loading the image.
  67. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  68. public init(_ url: URL?, options: KingfisherOptionsInfo? = nil) {
  69. self.init(source: url?.convertToSource(), options: options)
  70. }
  71. /// Declares the content and behavior of this view.
  72. public var body: some SwiftUI.View {
  73. Group {
  74. if binder.image != nil {
  75. configurations
  76. .reduce(SwiftUI.Image(crossPlatformImage: binder.image!)) {
  77. current, config in config(current)
  78. }
  79. } else {
  80. Group {
  81. if placeholder != nil {
  82. placeholder
  83. } else {
  84. SwiftUI.Image(crossPlatformImage: .init())
  85. }
  86. }
  87. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  88. .onDisappear { [weak binder = self.binder] in
  89. if self.cancelOnDisappear {
  90. binder?.cancel()
  91. }
  92. }
  93. }
  94. }.onAppear { [weak binder] in
  95. guard let binder = binder else {
  96. return
  97. }
  98. if !binder.loadingOrSuccessed {
  99. binder.start()
  100. }
  101. }
  102. }
  103. }
  104. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  105. extension KFImage {
  106. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  107. /// - Parameter block: The block applies to loaded image.
  108. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  109. public func configure(_ block: @escaping (SwiftUI.Image) -> SwiftUI.Image) -> KFImage {
  110. var result = self
  111. result.configurations.append(block)
  112. return result
  113. }
  114. public func resizable(
  115. capInsets: EdgeInsets = EdgeInsets(),
  116. resizingMode: SwiftUI.Image.ResizingMode = .stretch) -> KFImage
  117. {
  118. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  119. }
  120. public func renderingMode(_ renderingMode: SwiftUI.Image.TemplateRenderingMode?) -> KFImage {
  121. configure { $0.renderingMode(renderingMode) }
  122. }
  123. public func interpolation(_ interpolation: SwiftUI.Image.Interpolation) -> KFImage {
  124. configure { $0.interpolation(interpolation) }
  125. }
  126. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  127. configure { $0.antialiased(isAntialiased) }
  128. }
  129. /// Sets a placeholder `View` which shows when loading the image.
  130. /// - Parameter content: A view that describes the placeholder.
  131. /// - Returns: A `KFImage` view that contains `content` as its placeholder.
  132. public func placeholder<Content: SwiftUI.View>(@ViewBuilder _ content: () -> Content) -> KFImage {
  133. let v = content()
  134. var result = self
  135. result.placeholder = AnyView(v)
  136. return result
  137. }
  138. /// Sets cancelling the download task bound to `self` when the view disappearing.
  139. /// - Parameter flag: Whether cancel the task or not.
  140. /// - Returns: A `KFImage` view that cancels downloading task when disappears.
  141. public func cancelOnDisappear(_ flag: Bool) -> KFImage {
  142. var result = self
  143. result.cancelOnDisappear = flag
  144. return result
  145. }
  146. }
  147. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  148. extension KFImage {
  149. /// Sets the action to perform when the image setting fails.
  150. /// - Parameter action: The action to perform. If `action` is `nil`, the
  151. /// call has no effect.
  152. /// - Returns: A `KFImage` view that triggers `action` when setting image fails.
  153. public func onFailure(perform action: ((KingfisherError) -> Void)?) -> KFImage {
  154. binder.setOnFailure(perform: action)
  155. return self
  156. }
  157. /// Sets the action to perform when the image setting successes.
  158. /// - Parameter action: The action to perform. If `action` is `nil`, the
  159. /// call has no effect.
  160. /// - Returns: A `KFImage` view that triggers `action` when setting image successes.
  161. public func onSuccess(perform action: ((RetrieveImageResult) -> Void)?) -> KFImage {
  162. binder.setOnSuccess(perform: action)
  163. return self
  164. }
  165. /// Sets the action to perform when the image downloading progress receiving new data.
  166. /// - Parameter action: The action to perform. If `action` is `nil`, the
  167. /// call has no effect.
  168. /// - Returns: A `KFImage` view that triggers `action` when new data arrives when downloading.
  169. public func onProgress(perform action: ((Int64, Int64) -> Void)?) -> KFImage {
  170. binder.setOnProgress(perform: action)
  171. return self
  172. }
  173. }
  174. #if DEBUG
  175. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  176. struct KFImage_Previews : PreviewProvider {
  177. static var previews: some SwiftUI.View {
  178. Group {
  179. KFImage(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!)
  180. .onSuccess { r in
  181. print(r)
  182. }
  183. .resizable()
  184. .aspectRatio(contentMode: .fit)
  185. .padding()
  186. }
  187. }
  188. }
  189. #endif
  190. #endif