KFImage.swift 13 KB

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