KFImage.swift 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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 Image {
  31. // Creates an 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. // TODO: Replace `@ObservedObject` with `@StateObject` once we do not need to support iOS 13.
  45. /// An image binder that manages loading and cancelling image related task.
  46. @ObservedObject private(set) var binder: ImageBinder
  47. // Acts as a placeholder when loading an image.
  48. var placeholder: AnyView?
  49. // Whether the download task should be cancelled when the view disappears.
  50. var cancelOnDisappear: Bool = false
  51. // Configurations should be performed on the image.
  52. var configurations: [(Image) -> Image]
  53. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  54. /// - Parameter source: The image `Source` defining where to load the target image.
  55. /// - Parameter options: The options should be applied when loading the image.
  56. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  57. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  58. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  59. /// wrapped value from outside.
  60. /// - Deprecated: Some options are not available in SwiftUI yet. Use `KFImage(source:isLoaded:)` to create a
  61. /// `KFImage` and configure the options through modifier instead. See methods of `KFOptionSetter`
  62. /// for more.
  63. @available(*, deprecated, message: "Some options are not available in SwiftUI yet. Use `KFImage(source:isLoaded:)` to create a `KFImage` and configure the options through modifier instead.")
  64. public init(source: Source?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  65. let binder = ImageBinder(source: source, options: options, isLoaded: isLoaded)
  66. self.binder = binder
  67. configurations = []
  68. binder.start()
  69. }
  70. /// Creates a Kingfisher compatible image view to load image from the given `URL`.
  71. /// - Parameter url: The image URL from where to load the target image.
  72. /// - Parameter options: The options should be applied when loading the image.
  73. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  74. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  75. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  76. /// wrapped value from outside.
  77. /// - Deprecated: Some options are not available in SwiftUI yet. Use `KFImage(_:isLoaded:)` to create a
  78. /// `KFImage` and configure the options through modifier instead. See methods of `KFOptionSetter`
  79. /// for more.
  80. @available(*, deprecated, message: "Some options are not available in SwiftUI yet. Use `KFImage(_:isLoaded:)` to create a `KFImage` and configure the options through modifier instead.")
  81. public init(_ url: URL?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  82. self.init(source: url?.convertToSource(), options: options, isLoaded: isLoaded)
  83. }
  84. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  85. /// - Parameters:
  86. /// - source: The image `Source` defining where to load the target image.
  87. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  88. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  89. /// wrapped value from outside.
  90. public init(source: Source?, isLoaded: Binding<Bool> = .constant(false)) {
  91. let binder = ImageBinder(source: source, isLoaded: isLoaded)
  92. self.binder = binder
  93. configurations = []
  94. // Give the `binder` a chance to accept other configurations.
  95. DispatchQueue.main.async { binder.start() }
  96. }
  97. /// Creates a Kingfisher compatible image view to load image from the given `URL`.
  98. /// - Parameters:
  99. /// - source: The image `Source` defining where to load the target image.
  100. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  101. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  102. /// wrapped value from outside.
  103. public init(_ url: URL?, isLoaded: Binding<Bool> = .constant(false)) {
  104. self.init(source: url?.convertToSource(), isLoaded: isLoaded)
  105. }
  106. /// Declares the content and behavior of this view.
  107. public var body: some View {
  108. Group {
  109. if binder.image != nil {
  110. configurations
  111. .reduce(Image(crossPlatformImage: binder.image!)) {
  112. current, config in config(current)
  113. }
  114. } else {
  115. Group {
  116. if placeholder != nil {
  117. placeholder
  118. } else {
  119. Image(crossPlatformImage: .init())
  120. }
  121. }
  122. .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity)
  123. .onAppear { [weak binder = self.binder] in
  124. guard let binder = binder else {
  125. return
  126. }
  127. if !binder.loadingOrSucceeded {
  128. binder.start()
  129. }
  130. }
  131. .onDisappear { [weak binder = self.binder] in
  132. guard let binder = binder else {
  133. return
  134. }
  135. if self.cancelOnDisappear {
  136. binder.cancel()
  137. }
  138. }
  139. }
  140. }
  141. }
  142. }
  143. // MARK: - Image compatibility.
  144. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  145. extension KFImage {
  146. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  147. /// - Parameter block: The block applies to loaded image.
  148. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  149. public func configure(_ block: @escaping (Image) -> Image) -> KFImage {
  150. var result = self
  151. result.configurations.append(block)
  152. return result
  153. }
  154. public func resizable(
  155. capInsets: EdgeInsets = EdgeInsets(),
  156. resizingMode: Image.ResizingMode = .stretch) -> KFImage
  157. {
  158. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  159. }
  160. public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage {
  161. configure { $0.renderingMode(renderingMode) }
  162. }
  163. public func interpolation(_ interpolation: Image.Interpolation) -> KFImage {
  164. configure { $0.interpolation(interpolation) }
  165. }
  166. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  167. configure { $0.antialiased(isAntialiased) }
  168. }
  169. }
  170. #if DEBUG
  171. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  172. struct KFImage_Previews : PreviewProvider {
  173. static var previews: some View {
  174. Group {
  175. KFImage(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!)
  176. .onSuccess { r in
  177. print(r)
  178. }
  179. .resizable()
  180. .aspectRatio(contentMode: .fit)
  181. .padding()
  182. }
  183. }
  184. }
  185. #endif
  186. #endif