KFImage.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  41. public struct KFImage: View {
  42. var context: Context
  43. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  44. /// - Parameter source: The image `Source` defining where to load the target image.
  45. /// - Parameter options: The options should be applied when loading the image.
  46. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  47. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  48. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  49. /// wrapped value from outside.
  50. /// - Deprecated: Some options are not available in SwiftUI yet. Use `KFImage(source:isLoaded:)` to create a
  51. /// `KFImage` and configure the options through modifier instead. See methods of `KFOptionSetter`
  52. /// for more.
  53. @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.")
  54. public init(source: Source?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  55. let binder = KFImage.ImageBinder(source: source, options: options, isLoaded: isLoaded)
  56. self.init(binder: binder)
  57. }
  58. /// Creates a Kingfisher compatible image view to load image from the given `URL`.
  59. /// - Parameter url: The image URL from where to load the target image.
  60. /// - Parameter options: The options should be applied when loading the image.
  61. /// Some UIKit related options (such as `ImageTransition.flip`) are not supported.
  62. /// - Parameter isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  63. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  64. /// wrapped value from outside.
  65. /// - Deprecated: Some options are not available in SwiftUI yet. Use `KFImage(_:isLoaded:)` to create a
  66. /// `KFImage` and configure the options through modifier instead. See methods of `KFOptionSetter`
  67. /// for more.
  68. @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.")
  69. init(_ url: URL?, options: KingfisherOptionsInfo? = nil, isLoaded: Binding<Bool> = .constant(false)) {
  70. self.init(source: url?.convertToSource(), options: options, isLoaded: isLoaded)
  71. }
  72. /// Creates a Kingfisher compatible image view to load image from the given `Source`.
  73. /// - Parameters:
  74. /// - source: The image `Source` defining where to load the target image.
  75. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  76. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  77. /// wrapped value from outside.
  78. public init(source: Source?, isLoaded: Binding<Bool> = .constant(false)) {
  79. let binder = ImageBinder(source: source, isLoaded: isLoaded)
  80. self.init(binder: binder)
  81. }
  82. /// Creates a Kingfisher compatible image view to load image from the given `URL`.
  83. /// - Parameters:
  84. /// - source: The image `Source` defining where to load the target image.
  85. /// - isLoaded: Whether the image is loaded or not. This provides a way to inspect the internal loading
  86. /// state. `true` if the image is loaded successfully. Otherwise, `false`. Do not set the
  87. /// wrapped value from outside.
  88. public init(_ url: URL?, isLoaded: Binding<Bool> = .constant(false)) {
  89. self.init(source: url?.convertToSource(), isLoaded: isLoaded)
  90. }
  91. init(binder: ImageBinder) {
  92. self.context = Context(binder: binder)
  93. }
  94. public var body: some View {
  95. KFImageRenderer(context)
  96. .id(context.binder)
  97. }
  98. /// Starts the loading process of `self` immediately.
  99. ///
  100. /// By default, a `KFImage` will not load its source until the `onAppear` is called. This is a lazily loading
  101. /// behavior and provides better performance. However, when you refresh the view, the lazy loading also causes a
  102. /// flickering since the loading does not happen immediately. Call this method if you want to start the load at once
  103. /// could help avoiding the flickering, with some performance trade-off.
  104. ///
  105. /// - Returns: The `Self` value with changes applied.
  106. public func loadImmediately(_ start: Bool = true) -> KFImage {
  107. if start {
  108. context.binder.start()
  109. }
  110. return self
  111. }
  112. }
  113. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  114. extension KFImage {
  115. struct Context {
  116. var binder: ImageBinder
  117. var configurations: [(Image) -> Image] = []
  118. var cancelOnDisappear: Bool = false
  119. var placeholder: AnyView? = nil
  120. init(binder: ImageBinder) {
  121. self.binder = binder
  122. }
  123. }
  124. }
  125. /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`.
  126. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`.
  127. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  128. struct KFImageRenderer: View {
  129. /// An image binder that manages loading and cancelling image related task.
  130. @ObservedObject var binder: KFImage.ImageBinder
  131. // Acts as a placeholder when loading an image.
  132. var placeholder: AnyView?
  133. // Whether the download task should be cancelled when the view disappears.
  134. let cancelOnDisappear: Bool
  135. // Configurations should be performed on the image.
  136. let configurations: [(Image) -> Image]
  137. init(_ context: KFImage.Context) {
  138. self.binder = context.binder
  139. self.configurations = context.configurations
  140. self.placeholder = context.placeholder
  141. self.cancelOnDisappear = context.cancelOnDisappear
  142. }
  143. /// Declares the content and behavior of this view.
  144. var body: some View {
  145. if let image = binder.loadedImage {
  146. configurations
  147. .reduce(imageFromResult(image)) {
  148. current, config in config(current)
  149. }
  150. .opacity(binder.loaded ? 1.0 : 0.0)
  151. } else {
  152. Group {
  153. if placeholder != nil {
  154. placeholder
  155. } else {
  156. Color.clear
  157. }
  158. }
  159. .onAppear { [weak binder = self.binder] in
  160. guard let binder = binder else {
  161. return
  162. }
  163. if !binder.loadingOrSucceeded {
  164. binder.start()
  165. }
  166. }
  167. .onDisappear { [weak binder = self.binder] in
  168. guard let binder = binder else {
  169. return
  170. }
  171. if self.cancelOnDisappear {
  172. binder.cancel()
  173. }
  174. }
  175. }
  176. }
  177. private func imageFromResult(_ resultImage: KFCrossPlatformImage) -> Image {
  178. if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
  179. return Image(crossPlatformImage: resultImage)
  180. } else {
  181. #if canImport(UIKit)
  182. // The CG image is used to solve #1395
  183. // It should be not necessary if SwiftUI.Image can handle resizing correctly when created
  184. // by `Image.init(uiImage:)`. (The orientation information should be already contained in
  185. // a `UIImage`)
  186. // https://github.com/onevcat/Kingfisher/issues/1395
  187. //
  188. // This issue happens on iOS 13 and was fixed by Apple from iOS 14.
  189. if let cgImage = resultImage.cgImage {
  190. return Image(decorative: cgImage, scale: resultImage.scale, orientation: resultImage.imageOrientation.toSwiftUI())
  191. } else {
  192. return Image(crossPlatformImage: resultImage)
  193. }
  194. #else
  195. return Image(crossPlatformImage: resultImage)
  196. #endif
  197. }
  198. }
  199. }
  200. #if canImport(UIKit)
  201. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  202. extension UIImage.Orientation {
  203. func toSwiftUI() -> Image.Orientation {
  204. switch self {
  205. case .down: return .down
  206. case .up: return .up
  207. case .left: return .left
  208. case .right: return .right
  209. case .upMirrored: return .upMirrored
  210. case .downMirrored: return .downMirrored
  211. case .leftMirrored: return .leftMirrored
  212. case .rightMirrored: return .rightMirrored
  213. @unknown default: return .up
  214. }
  215. }
  216. }
  217. #endif
  218. // MARK: - Image compatibility.
  219. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  220. extension KFImage {
  221. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  222. /// - Parameter block: The block applies to loaded image.
  223. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  224. public func configure(_ block: @escaping (Image) -> Image) -> KFImage {
  225. var result = self
  226. result.context.configurations.append(block)
  227. return result
  228. }
  229. public func resizable(
  230. capInsets: EdgeInsets = EdgeInsets(),
  231. resizingMode: Image.ResizingMode = .stretch) -> KFImage
  232. {
  233. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  234. }
  235. public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage {
  236. configure { $0.renderingMode(renderingMode) }
  237. }
  238. public func interpolation(_ interpolation: Image.Interpolation) -> KFImage {
  239. configure { $0.interpolation(interpolation) }
  240. }
  241. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  242. configure { $0.antialiased(isAntialiased) }
  243. }
  244. }
  245. #if DEBUG
  246. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  247. struct KFImage_Previews : PreviewProvider {
  248. static var previews: some View {
  249. Group {
  250. KFImage(source: .network(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!))
  251. .onSuccess { r in
  252. print(r)
  253. }
  254. .resizable()
  255. .aspectRatio(contentMode: .fit)
  256. .padding()
  257. }
  258. }
  259. }
  260. #endif
  261. #endif