KFImage.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  30. extension SwiftUI.Image {
  31. // Creates an SwiftUI.Image with either UIImage or NSImage.
  32. init(crossPlatformImage: KFCrossPlatformImage) {
  33. #if canImport(UIKit)
  34. self.init(uiImage: crossPlatformImage)
  35. #elseif canImport(AppKit)
  36. self.init(nsImage: crossPlatformImage)
  37. #endif
  38. }
  39. }
  40. /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`.
  41. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`.
  42. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  43. public struct KFImage: SwiftUI.View {
  44. /// An image binder that manages loading and cancelling image related task.
  45. @ObservedObject public private(set) var binder: ImageBinder
  46. // Acts as a placeholder when loading an image.
  47. var placeholder: AnyView?
  48. // Whether the download task should be cancelled when the view disappears.
  49. var cancelOnDisappear: Bool = false
  50. // Configurations should be performed on the image.
  51. var configurations: [(SwiftUI.Image) -> SwiftUI.Image]
  52. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  53. /// - Parameter source: The image `Source` defining where to load the target image.
  54. /// - Parameter options: The options should be applied when loading the image.
  55. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  56. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  57. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  58. /// wrapped value from outside.
  59. public init(source: Source?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  60. binder = ImageBinder(source: source, options: options, isLoaded: isLoaded)
  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. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  69. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  70. /// wrapped value from outside.
  71. public init(_ url: URL?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  72. self.init(source: url?.convertToSource(), options: options, isLoaded: isLoaded)
  73. }
  74. /// Declares the content and behavior of this view.
  75. public var body: some SwiftUI.View {
  76. Group {
  77. if binder.image != nil {
  78. configurations
  79. .reduce(SwiftUI.Image(crossPlatformImage: binder.image!)) {
  80. current, config in config(current)
  81. }
  82. } else {
  83. Group {
  84. if placeholder != nil {
  85. placeholder
  86. } else {
  87. SwiftUI.Image(crossPlatformImage: .init())
  88. }
  89. }
  90. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  91. .onAppear { [weak binder = self.binder] in
  92. guard let binder = binder else {
  93. return
  94. }
  95. if !binder.loadingOrSucceeded {
  96. binder.start()
  97. }
  98. }
  99. .onDisappear { [weak binder = self.binder] in
  100. guard let binder = binder else {
  101. return
  102. }
  103. if self.cancelOnDisappear {
  104. binder.cancel()
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  112. extension KFImage {
  113. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  114. /// - Parameter block: The block applies to loaded image.
  115. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  116. public func configure(_ block: @escaping (SwiftUI.Image) -> SwiftUI.Image) -> KFImage {
  117. var result = self
  118. result.configurations.append(block)
  119. return result
  120. }
  121. public func resizable(
  122. capInsets: EdgeInsets = EdgeInsets(),
  123. resizingMode: SwiftUI.Image.ResizingMode = .stretch) -> KFImage
  124. {
  125. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  126. }
  127. public func renderingMode(_ renderingMode: SwiftUI.Image.TemplateRenderingMode?) -> KFImage {
  128. configure { $0.renderingMode(renderingMode) }
  129. }
  130. public func interpolation(_ interpolation: SwiftUI.Image.Interpolation) -> KFImage {
  131. configure { $0.interpolation(interpolation) }
  132. }
  133. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  134. configure { $0.antialiased(isAntialiased) }
  135. }
  136. /// Sets a placeholder `View` which shows when loading the image.
  137. /// - Parameter content: A view that describes the placeholder.
  138. /// - Returns: A `KFImage` view that contains `content` as its placeholder.
  139. public func placeholder<Content: SwiftUI.View>(@ViewBuilder _ content: () -> Content) -> KFImage {
  140. let v = content()
  141. var result = self
  142. result.placeholder = AnyView(v)
  143. return result
  144. }
  145. /// Sets cancelling the download task bound to `self` when the view disappearing.
  146. /// - Parameter flag: Whether cancel the task or not.
  147. /// - Returns: A `KFImage` view that cancels downloading task when disappears.
  148. public func cancelOnDisappear(_ flag: Bool) -> KFImage {
  149. var result = self
  150. result.cancelOnDisappear = flag
  151. return result
  152. }
  153. }
  154. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  155. extension KFImage {
  156. /// Sets the action to perform when the image setting fails.
  157. /// - Parameter action: The action to perform. If `action` is `nil`, the
  158. /// call has no effect.
  159. /// - Returns: A `KFImage` view that triggers `action` when setting image fails.
  160. public func onFailure(perform action: ((KingfisherError) -> Void)?) -> KFImage {
  161. binder.setOnFailure(perform: action)
  162. return self
  163. }
  164. /// Sets the action to perform when the image setting successes.
  165. /// - Parameter action: The action to perform. If `action` is `nil`, the
  166. /// call has no effect.
  167. /// - Returns: A `KFImage` view that triggers `action` when setting image successes.
  168. public func onSuccess(perform action: ((RetrieveImageResult) -> Void)?) -> KFImage {
  169. binder.setOnSuccess(perform: action)
  170. return self
  171. }
  172. /// Sets the action to perform when the image downloading progress receiving new data.
  173. /// - Parameter action: The action to perform. If `action` is `nil`, the
  174. /// call has no effect.
  175. /// - Returns: A `KFImage` view that triggers `action` when new data arrives when downloading.
  176. public func onProgress(perform action: ((Int64, Int64) -> Void)?) -> KFImage {
  177. binder.setOnProgress(perform: action)
  178. return self
  179. }
  180. }
  181. #if DEBUG
  182. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  183. struct KFImage_Previews : PreviewProvider {
  184. static var previews: some SwiftUI.View {
  185. Group {
  186. KFImage(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!)
  187. .onSuccess { r in
  188. print(r)
  189. }
  190. .resizable()
  191. .aspectRatio(contentMode: .fit)
  192. .padding()
  193. }
  194. }
  195. }
  196. #endif
  197. #endif