KFImage.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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. public func loadImmediately() -> KFImage {
  99. context.binder.start()
  100. return self
  101. }
  102. }
  103. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  104. extension KFImage {
  105. struct Context {
  106. var binder: ImageBinder
  107. var configurations: [(Image) -> Image] = []
  108. var cancelOnDisappear: Bool = false
  109. var placeholder: AnyView? = nil
  110. init(binder: ImageBinder) {
  111. self.binder = binder
  112. }
  113. }
  114. }
  115. /// A Kingfisher compatible SwiftUI `View` to load an image from a `Source`.
  116. /// Declaring a `KFImage` in a `View`'s body to trigger loading from the given `Source`.
  117. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  118. struct KFImageRenderer: View {
  119. /// An image binder that manages loading and cancelling image related task.
  120. @ObservedObject var binder: KFImage.ImageBinder
  121. // Acts as a placeholder when loading an image.
  122. var placeholder: AnyView?
  123. // Whether the download task should be cancelled when the view disappears.
  124. let cancelOnDisappear: Bool
  125. // Configurations should be performed on the image.
  126. let configurations: [(Image) -> Image]
  127. init(_ context: KFImage.Context) {
  128. self.binder = context.binder
  129. self.configurations = context.configurations
  130. self.placeholder = context.placeholder
  131. self.cancelOnDisappear = context.cancelOnDisappear
  132. }
  133. /// Declares the content and behavior of this view.
  134. var body: some View {
  135. if let image = binder.loadedImage {
  136. configurations
  137. .reduce(imageFromResult(image)) {
  138. current, config in config(current)
  139. }
  140. .opacity(binder.loaded ? 1.0 : 0.0)
  141. } else {
  142. Group {
  143. if placeholder != nil {
  144. placeholder
  145. } else {
  146. Color.clear
  147. }
  148. }
  149. .onAppear { [weak binder = self.binder] in
  150. guard let binder = binder else {
  151. return
  152. }
  153. if !binder.loadingOrSucceeded {
  154. binder.start()
  155. }
  156. }
  157. .onDisappear { [weak binder = self.binder] in
  158. guard let binder = binder else {
  159. return
  160. }
  161. if self.cancelOnDisappear {
  162. binder.cancel()
  163. }
  164. }
  165. }
  166. }
  167. private func imageFromResult(_ resultImage: KFCrossPlatformImage) -> Image {
  168. if #available(macOS 11.0, iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
  169. return Image(crossPlatformImage: resultImage)
  170. } else {
  171. #if canImport(UIKit)
  172. // The CG image is used to solve #1395
  173. // It should be not necessary if SwiftUI.Image can handle resizing correctly when created
  174. // by `Image.init(uiImage:)`. (The orientation information should be already contained in
  175. // a `UIImage`)
  176. // https://github.com/onevcat/Kingfisher/issues/1395
  177. //
  178. // This issue happens on iOS 13 and was fixed by Apple from iOS 14.
  179. if let cgImage = resultImage.cgImage {
  180. return Image(decorative: cgImage, scale: resultImage.scale, orientation: resultImage.imageOrientation.toSwiftUI())
  181. } else {
  182. return Image(crossPlatformImage: resultImage)
  183. }
  184. #else
  185. return Image(crossPlatformImage: resultImage)
  186. #endif
  187. }
  188. }
  189. }
  190. #if canImport(UIKit)
  191. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  192. extension UIImage.Orientation {
  193. func toSwiftUI() -> Image.Orientation {
  194. switch self {
  195. case .down: return .down
  196. case .up: return .up
  197. case .left: return .left
  198. case .right: return .right
  199. case .upMirrored: return .upMirrored
  200. case .downMirrored: return .downMirrored
  201. case .leftMirrored: return .leftMirrored
  202. case .rightMirrored: return .rightMirrored
  203. @unknown default: return .up
  204. }
  205. }
  206. }
  207. #endif
  208. // MARK: - Image compatibility.
  209. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  210. extension KFImage {
  211. /// Configures current image with a `block`. This block will be lazily applied when creating the final `Image`.
  212. /// - Parameter block: The block applies to loaded image.
  213. /// - Returns: A `KFImage` view that configures internal `Image` with `block`.
  214. public func configure(_ block: @escaping (Image) -> Image) -> KFImage {
  215. var result = self
  216. result.context.configurations.append(block)
  217. return result
  218. }
  219. public func resizable(
  220. capInsets: EdgeInsets = EdgeInsets(),
  221. resizingMode: Image.ResizingMode = .stretch) -> KFImage
  222. {
  223. configure { $0.resizable(capInsets: capInsets, resizingMode: resizingMode) }
  224. }
  225. public func renderingMode(_ renderingMode: Image.TemplateRenderingMode?) -> KFImage {
  226. configure { $0.renderingMode(renderingMode) }
  227. }
  228. public func interpolation(_ interpolation: Image.Interpolation) -> KFImage {
  229. configure { $0.interpolation(interpolation) }
  230. }
  231. public func antialiased(_ isAntialiased: Bool) -> KFImage {
  232. configure { $0.antialiased(isAntialiased) }
  233. }
  234. }
  235. #if DEBUG
  236. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  237. struct KFImage_Previews : PreviewProvider {
  238. static var previews: some View {
  239. Group {
  240. KFImage(source: .network(URL(string: "https://raw.githubusercontent.com/onevcat/Kingfisher/master/images/logo.png")!))
  241. .onSuccess { r in
  242. print(r)
  243. }
  244. .resizable()
  245. .aspectRatio(contentMode: .fit)
  246. .padding()
  247. }
  248. }
  249. }
  250. #endif
  251. #endif