KFImage.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. import SwiftUI
  27. import Combine
  28. import Kingfisher
  29. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  30. extension 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: View {
  44. /// An image binder that manages loading and cancelling image related task.
  45. @ObjectBinding 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: [(Image) -> 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. public init(_ source: Source, options: KingfisherOptionsInfo? = nil) {
  57. binder = ImageBinder(source: source, options: options)
  58. configurations = []
  59. }
  60. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  61. /// - Parameter url: The image URL from where to load the target image.
  62. /// - Parameter options: The options should be applied when loading the image.
  63. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  64. public init(_ url: URL, options: KingfisherOptionsInfo? = nil) {
  65. self.init(.network(url), options: options)
  66. }
  67. /// Declares the content and behavior of this view.
  68. public var body: some View {
  69. ZStack {
  70. if binder.image != nil {
  71. configurations
  72. .reduce(Image(crossPlatformImage: binder.image!)) {
  73. current, config in config(current)
  74. }
  75. .animation(binder.fadeTransitionAnimation)
  76. } else {
  77. (placeholder ?? AnyView(Image(crossPlatformImage: .init())))
  78. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  79. .onDisappear { [unowned binder = self.binder] in
  80. if self.cancelOnDisappear { binder.cancel() }
  81. }
  82. }
  83. }.onAppear { [unowned binder] in
  84. binder.start()
  85. }
  86. }
  87. }
  88. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  89. extension KFImage {
  90. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  91. /// - Parameter block: The block applies to loaded image.
  92. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  93. public func configure(_ block: @escaping (Image) -> Image) -> KFImage {
  94. var result = self
  95. result.configurations.append(block)
  96. return result
  97. }
  98. public func resizable(
  99. capInsets: EdgeInsets = EdgeInsets(),
  100. resizingMode: Image.ResizingMode = .stretch) -> KFImage
  101. {
  102. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  103. }
  104. public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage {
  105. configure { $0.renderingMode(renderingMode) }
  106. }
  107. public func interpolation(_ interpolation: Image.Interpolation) -> KFImage {
  108. configure { $0.interpolation(interpolation) }
  109. }
  110. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  111. configure { $0.antialiased(isAntialiased) }
  112. }
  113. /// Sets a placeholder `View` which shows when loading the image.
  114. /// - Parameter content: A view that describes the placeholder.
  115. /// - Returns: A `KFImage` view that contains `content` as its placeholder.
  116. public func placeholder<Content: View>(@ViewBuilder _ content: () -> Content) -> KFImage {
  117. let v = content()
  118. var result = self
  119. result.placeholder = AnyView(v)
  120. return result
  121. }
  122. /// Sets cancelling the download task bound to `self` when the view disappearing.
  123. /// - Parameter flag: Whether cancel the task or not.
  124. /// - Returns: A `KFImage` view that cancels downloading task when disappears.
  125. public func cancelOnDisappear(_ flag: Bool) -> KFImage {
  126. var result = self
  127. result.cancelOnDisappear = flag
  128. return result
  129. }
  130. }
  131. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  132. extension KFImage {
  133. /// Sets the action to perform when the image setting fails.
  134. /// - Parameter action: The action to perform. If `action` is `nil`, the
  135. /// call has no effect.
  136. /// - Returns: A `KFImage` view that triggers `action` when setting image fails.
  137. public func onFailure(perform action: ((KingfisherError) -> Void)?) -> KFImage {
  138. binder.setOnFailure(perform: action)
  139. return self
  140. }
  141. /// Sets the action to perform when the image setting successes.
  142. /// - Parameter action: The action to perform. If `action` is `nil`, the
  143. /// call has no effect.
  144. /// - Returns: A `KFImage` view that triggers `action` when setting image successes.
  145. public func onSuccess(perform action: ((RetrieveImageResult) -> Void)?) -> KFImage {
  146. binder.setOnSuccess(perform: action)
  147. return self
  148. }
  149. /// Sets the action to perform when the image downloading progress receiving new data.
  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 new data arrives when downloading.
  153. public func onProgress(perform action: ((Int64, Int64) -> Void)?) -> KFImage {
  154. binder.setOnProgress(perform: action)
  155. return self
  156. }
  157. }
  158. #if DEBUG
  159. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  160. struct KFImage_Previews : PreviewProvider {
  161. static var previews: some View {
  162. Group {
  163. KFImage(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!)
  164. .onSuccess { r in
  165. print(r)
  166. }
  167. .resizable()
  168. .aspectRatio(contentMode: .fit)
  169. .padding()
  170. }
  171. }
  172. }
  173. #endif