KFImage.swift 7.9 KB

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