KFOptionsSetter.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. //
  2. // KFOptionsSetter.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2020/12/22.
  6. //
  7. // Copyright (c) 2020 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 Foundation
  27. import CoreGraphics
  28. public protocol KFOptionSetter {
  29. var options: KingfisherParsedOptionsInfo { get nonmutating set }
  30. var onFailureDelegate: Delegate<KingfisherError, Void> { get }
  31. var onSuccessDelegate: Delegate<RetrieveImageResult, Void> { get }
  32. var onProgressDelegate: Delegate<(Int64, Int64), Void> { get }
  33. var delegateObserver: AnyObject { get }
  34. }
  35. extension KF.Builder: KFOptionSetter {
  36. public var delegateObserver: AnyObject { self }
  37. }
  38. #if canImport(SwiftUI) && canImport(Combine)
  39. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *)
  40. extension KFImage: KFOptionSetter {
  41. public var options: KingfisherParsedOptionsInfo {
  42. get { binder.options }
  43. nonmutating set { binder.options = newValue }
  44. }
  45. public var onFailureDelegate: Delegate<KingfisherError, Void> { binder.onFailureDelegate }
  46. public var onSuccessDelegate: Delegate<RetrieveImageResult, Void> { binder.onSuccessDelegate }
  47. public var onProgressDelegate: Delegate<(Int64, Int64), Void> { binder.onProgressDelegate }
  48. public var delegateObserver: AnyObject { binder }
  49. }
  50. #endif
  51. // MARK: - Life cycles
  52. extension KFOptionSetter {
  53. /// Sets the progress block to current builder.
  54. /// - Parameter block: Called when the image downloading progress gets updated. If the response does not contain an
  55. /// `expectedContentLength`, this block will not be called. If `block` is `nil`, the callback
  56. /// will be reset.
  57. /// - Returns: A `Self` value with changes applied.
  58. public func onProgress(_ block: DownloadProgressBlock?) -> Self {
  59. onProgressDelegate.delegate(on: delegateObserver) { (observer, result) in
  60. block?(result.0, result.1)
  61. }
  62. return self
  63. }
  64. /// Sets the the done block to current builder.
  65. /// - Parameter block: Called when the image task successfully completes and the the image set is done. If `block`
  66. /// is `nil`, the callback will be reset.
  67. /// - Returns: A `KF.Builder` with changes applied.
  68. public func onSuccess(_ block: ((RetrieveImageResult) -> Void)?) -> Self {
  69. onSuccessDelegate.delegate(on: delegateObserver) { (observer, result) in
  70. block?(result)
  71. }
  72. return self
  73. }
  74. /// Sets the catch block to current builder.
  75. /// - Parameter block: Called when an error happens during the image task. If `block`
  76. /// is `nil`, the callback will be reset.
  77. /// - Returns: A `KF.Builder` with changes applied.
  78. public func onFailure(_ block: ((KingfisherError) -> Void)?) -> Self {
  79. onFailureDelegate.delegate(on: delegateObserver) { (observer, error) in
  80. block?(error)
  81. }
  82. return self
  83. }
  84. }
  85. // MARK: - Basic options settings.
  86. extension KFOptionSetter {
  87. /// Sets the target image cache for this task.
  88. /// - Parameter cache: The target cache is about to be used for the task.
  89. /// - Returns: A `Self` value with changes applied.
  90. ///
  91. /// Kingfisher will use the associated `ImageCache` object when handling related operations,
  92. /// including trying to retrieve the cached images and store the downloaded image to it.
  93. ///
  94. public func targetCache(_ cache: ImageCache) -> Self {
  95. options.targetCache = cache
  96. return self
  97. }
  98. /// Sets the target image cache to store the original downloaded image for this task.
  99. /// - Parameter cache: The target cache is about to be used for storing the original downloaded image from the task.
  100. /// - Returns: A `Self` value with changes applied.
  101. ///
  102. /// The `ImageCache` for storing and retrieving original images. If `originalCache` is
  103. /// contained in the options, it will be preferred for storing and retrieving original images.
  104. /// If there is no `.originalCache` in the options, `.targetCache` will be used to store original images.
  105. ///
  106. /// When using KingfisherManager to download and store an image, if `cacheOriginalImage` is
  107. /// applied in the option, the original image will be stored to this `originalCache`. At the
  108. /// same time, if a requested final image (with processor applied) cannot be found in `targetCache`,
  109. /// Kingfisher will try to search the original image to check whether it is already there. If found,
  110. /// it will be used and applied with the given processor. It is an optimization for not downloading
  111. /// the same image for multiple times.
  112. ///
  113. public func originalCache(_ cache: ImageCache) -> Self {
  114. options.originalCache = cache
  115. return self
  116. }
  117. /// Sets the downloader used to perform the image download task.
  118. /// - Parameter downloader: The downloader which is about to be used for downloading.
  119. /// - Returns: A `Self` value with changes applied.
  120. ///
  121. /// Kingfisher will use the set `ImageDownloader` object to download the requested images.
  122. public func downloader(_ downloader: ImageDownloader) -> Self {
  123. options.downloader = downloader
  124. return self
  125. }
  126. /// Sets the download priority for the image task.
  127. /// - Parameter priority: The download priority of image download task.
  128. /// - Returns: A `Self` value with changes applied.
  129. ///
  130. /// The `priority` value will be set as the priority of the image download task. The value for it should be
  131. /// between 0.0~1.0. You can choose a value between `URLSessionTask.defaultPriority`, `URLSessionTask.lowPriority`
  132. /// or `URLSessionTask.highPriority`. If this option not set, the default value (`URLSessionTask.defaultPriority`)
  133. /// will be used.
  134. public func downloadPriority(_ priority: Float) -> Self {
  135. options.downloadPriority = priority
  136. return self
  137. }
  138. /// Sets whether Kingfisher should ignore the cache and try to start a download task for the image source.
  139. /// - Parameter enabled: Enable the force refresh or not.
  140. /// - Returns: A `Self` value with changes applied.
  141. public func forceRefresh(_ enabled: Bool = true) -> Self {
  142. options.forceRefresh = enabled
  143. return self
  144. }
  145. /// Sets whether Kingfisher should try to retrieve the image from memory cache first. If not found, it ignores the
  146. /// disk cache and starts a download task for the image source.
  147. /// - Parameter enabled: Enable the memory-only cache searching or not.
  148. /// - Returns: A `Self` value with changes applied.
  149. ///
  150. /// This is useful when you want to display a changeable image behind the same url at the same app session, while
  151. /// avoiding download it for multiple times.
  152. public func fromMemoryCacheOrRefresh(_ enabled: Bool = true) -> Self {
  153. options.fromMemoryCacheOrRefresh = enabled
  154. return self
  155. }
  156. /// Sets whether the image should only be cached in memory but not in disk.
  157. /// - Parameter enabled: Whether the image should be only cache in memory or not.
  158. /// - Returns: A `Self` value with changes applied.
  159. public func cacheMemoryOnly(_ enabled: Bool = true) -> Self {
  160. options.cacheMemoryOnly = enabled
  161. return self
  162. }
  163. /// Sets whether Kingfisher should wait for caching operation to be completed before calling the
  164. /// `onSuccess` or `onFailure` block.
  165. /// - Parameter enabled: Whether Kingfisher should wait for caching operation.
  166. /// - Returns: A `Self` value with changes applied.
  167. public func waitForCache(_ enabled: Bool = true) -> Self {
  168. options.waitForCache = enabled
  169. return self
  170. }
  171. /// Sets whether Kingfisher should only try to retrieve the image from cache, but not from network.
  172. /// - Parameter enabled: Whether Kingfisher should only try to retrieve the image from cache.
  173. /// - Returns: A `Self` value with changes applied.
  174. ///
  175. /// If the image is not in cache, the image retrieving will fail with the
  176. /// `KingfisherError.cacheError` with `.imageNotExisting` as its reason.
  177. public func onlyFromCache(_ enabled: Bool = true) -> Self {
  178. options.onlyFromCache = enabled
  179. return self
  180. }
  181. /// Sets whether the image should be decoded in a background thread before using.
  182. /// - Parameter enabled: Whether the image should be decoded in a background thread before using.
  183. /// - Returns: A `Self` value with changes applied.
  184. ///
  185. /// Setting to `true` will decode the downloaded image data and do a off-screen rendering to extract pixel
  186. /// information in background. This can speed up display, but will cost more time and memory to prepare the image
  187. /// for using.
  188. public func backgroundDecode(_ enabled: Bool = true) -> Self {
  189. options.backgroundDecode = enabled
  190. return self
  191. }
  192. /// Sets the callback queue which is used as the target queue of dispatch callbacks when retrieving images from
  193. /// cache. If not set, Kingfisher will use main queue for callbacks.
  194. /// - Parameter queue: The target queue which the cache retrieving callback will be invoked on.
  195. /// - Returns: A `Self` value with changes applied.
  196. ///
  197. /// - Note:
  198. /// This option does not affect the callbacks for UI related extension methods. You will always get the
  199. /// callbacks called from main queue.
  200. public func callbackQueue(_ queue: CallbackQueue) -> Self {
  201. options.callbackQueue = queue
  202. return self
  203. }
  204. /// Sets the scale factor value when converting retrieved data to an image.
  205. /// - Parameter factor: The scale factor value.
  206. /// - Returns: A `Self` value with changes applied.
  207. ///
  208. /// Specify the image scale, instead of your screen scale. You may need to set the correct scale when you dealing
  209. /// with 2x or 3x retina images. Otherwise, Kingfisher will convert the data to image object at `scale` 1.0.
  210. ///
  211. public func scaleFactor(_ factor: CGFloat) -> Self {
  212. options.scaleFactor = factor
  213. return self
  214. }
  215. /// Sets whether the original image should be cached even when the original image has been processed by any other
  216. /// `ImageProcessor`s.
  217. /// - Parameter enabled: Whether the original image should be cached.
  218. /// - Returns: A `Self` value with changes applied.
  219. ///
  220. /// If set and an `ImageProcessor` is used, Kingfisher will try to cache both the final result and original
  221. /// image. Kingfisher will have a chance to use the original image when another processor is applied to the same
  222. /// resource, instead of downloading it again. You can use `.originalCache` to specify a cache or the original
  223. /// images if necessary.
  224. ///
  225. /// The original image will be only cached to disk storage.
  226. ///
  227. public func cacheOriginalImage(_ enabled: Bool = true) -> Self {
  228. options.cacheOriginalImage = enabled
  229. return self
  230. }
  231. /// Sets whether the disk storage loading should happen in the same calling queue.
  232. /// - Parameter enabled: Whether the disk storage loading should happen in the same calling queue.
  233. /// - Returns: A `Self` value with changes applied.
  234. ///
  235. /// By default, disk storage file loading
  236. /// happens in its own queue with an asynchronous dispatch behavior. Although it provides better non-blocking disk
  237. /// loading performance, it also causes a flickering when you reload an image from disk, if the image view already
  238. /// has an image set.
  239. ///
  240. /// Set this options will stop that flickering by keeping all loading in the same queue (typically the UI queue
  241. /// if you are using Kingfisher's extension methods to set an image), with a tradeoff of loading performance.
  242. ///
  243. public func loadDiskFileSynchronously(_ enabled: Bool = true) -> Self {
  244. options.loadDiskFileSynchronously = enabled
  245. return self
  246. }
  247. /// Sets a queue on which the image processing should happen.
  248. /// - Parameter queue: The queue on which the image processing should happen.
  249. /// - Returns: A `Self` value with changes applied.
  250. ///
  251. /// By default, Kingfisher uses a pre-defined serial
  252. /// queue to process images. Use this option to change this behavior. For example, specify a `.mainCurrentOrAsync`
  253. /// to let the image be processed in main queue to prevent a possible flickering (but with a possibility of
  254. /// blocking the UI, especially if the processor needs a lot of time to run).
  255. public func processingQueue(_ queue: CallbackQueue?) -> Self {
  256. options.processingQueue = queue
  257. return self
  258. }
  259. /// Sets the alternative sources that will be used when loading of the original input `Source` fails.
  260. /// - Parameter sources: The alternative sources will be used.
  261. /// - Returns: A `Self` value with changes applied.
  262. ///
  263. /// Values of the `sources` array will be used to start a new image loading task if the previous task
  264. /// fails due to an error. The image source loading process will stop as soon as a source is loaded successfully.
  265. /// If all `sources` are used but the loading is still failing, an `imageSettingError` with
  266. /// `alternativeSourcesExhausted` as its reason will be given out in the `catch` block.
  267. ///
  268. /// This is useful if you want to implement a fallback solution for setting image.
  269. ///
  270. /// User cancellation will not trigger the alternative source loading.
  271. public func alternativeSources(_ sources: [Source]?) -> Self {
  272. options.alternativeSources = sources
  273. return self
  274. }
  275. /// Sets a retry strategy that will be used when something gets wrong during the image retrieving.
  276. /// - Parameter strategy: The provided strategy to define how the retrying should happen.
  277. /// - Returns: A `Self` value with changes applied.
  278. public func retry(_ strategy: RetryStrategy) -> Self {
  279. options.retryStrategy = strategy
  280. return self
  281. }
  282. /// Sets a retry strategy with a max retry count and retrying interval.
  283. /// - Parameters:
  284. /// - maxCount: The maximum count before the retry stops.
  285. /// - interval: The time interval between each retry attempt.
  286. /// - Returns: A `Self` value with changes applied.
  287. ///
  288. /// This defines the simplest retry strategy, which retry a failing request for several times, with some certain
  289. /// interval between each time. For example, `.retry(maxCount: 3, interval: .second(3))` means attempt for at most
  290. /// three times, and wait for 3 seconds if a previous retry attempt fails, then start a new attempt.
  291. public func retry(maxCount: Int, interval: DelayRetryStrategy.Interval = .seconds(3)) -> Self {
  292. let strategy = DelayRetryStrategy(maxRetryCount: maxCount, retryInterval: interval)
  293. options.retryStrategy = strategy
  294. return self
  295. }
  296. /// Sets the `Source` should be loaded when user enables Low Data Mode and the original source fails with an
  297. /// `NSURLErrorNetworkUnavailableReason.constrained` error.
  298. /// - Parameter source: The `Source` will be loaded under low data mode.
  299. /// - Returns: A `Self` value with changes applied.
  300. ///
  301. /// When this option is set, the
  302. /// `allowsConstrainedNetworkAccess` property of the request for the original source will be set to `false` and the
  303. /// `Source` in associated value will be used to retrieve the image for low data mode. Usually, you can provide a
  304. /// low-resolution version of your image or a local image provider to display a placeholder.
  305. ///
  306. /// If not set or the `source` is `nil`, the device Low Data Mode will be ignored and the original source will
  307. /// be loaded following the system default behavior, in a normal way.
  308. public func lowDataModeSource(_ source: Source?) -> Self {
  309. options.lowDataModeSource = source
  310. return self
  311. }
  312. }
  313. // MARK: - Request Modifier
  314. extension KFOptionSetter {
  315. /// Sets an `ImageDownloadRequestModifier` to change the image download request before it being sent.
  316. /// - Parameter modifier: The modifier will be used to change the request before it being sent.
  317. /// - Returns: A `Self` value with changes applied.
  318. ///
  319. /// This is the last chance you can modify the image download request. You can modify the request for some
  320. /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
  321. ///
  322. public func requestModifier(_ modifier: ImageDownloadRequestModifier) -> Self {
  323. options.requestModifier = modifier
  324. return self
  325. }
  326. /// Sets a block to change the image download request before it being sent.
  327. /// - Parameter modifyBlock: The modifying block will be called to change the request before it being sent.
  328. /// - Returns: A `Self` value with changes applied.
  329. ///
  330. /// This is the last chance you can modify the image download request. You can modify the request for some
  331. /// customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url mapping.
  332. ///
  333. public func requestModifier(_ modifyBlock: @escaping (inout URLRequest) -> Void) -> Self {
  334. options.requestModifier = AnyModifier { r -> URLRequest? in
  335. var request = r
  336. modifyBlock(&request)
  337. return request
  338. }
  339. return self
  340. }
  341. }
  342. // MARK: - Redirect Handler
  343. extension KFOptionSetter {
  344. /// The `ImageDownloadRedirectHandler` argument will be used to change the request before redirection.
  345. /// This is the possibility you can modify the image download request during redirect. You can modify the request for
  346. /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
  347. /// mapping.
  348. /// The original redirection request will be sent without any modification by default.
  349. /// - Parameter handler: The handler will be used for redirection.
  350. /// - Returns: A `Self` value with changes applied.
  351. public func redirectHandler(_ handler: ImageDownloadRedirectHandler) -> Self {
  352. options.redirectHandler = handler
  353. return self
  354. }
  355. /// The `block` will be used to change the request before redirection.
  356. /// This is the possibility you can modify the image download request during redirect. You can modify the request for
  357. /// some customizing purpose, such as adding auth token to the header, do basic HTTP auth or something like url
  358. /// mapping.
  359. /// The original redirection request will be sent without any modification by default.
  360. /// - Parameter block: The block will be used for redirection.
  361. /// - Returns: A `Self` value with changes applied.
  362. public func redirectHandler(_ block: @escaping (KF.RedirectPayload) -> Void) -> Self {
  363. let redirectHandler = AnyRedirectHandler { (task, response, request, handler) in
  364. let payload = KF.RedirectPayload(
  365. task: task, response: response, newRequest: request, completionHandler: handler
  366. )
  367. block(payload)
  368. }
  369. options.redirectHandler = redirectHandler
  370. return self
  371. }
  372. }
  373. // MARK: - Processor
  374. extension KFOptionSetter {
  375. /// Sets an image processor for the image task. It replaces the current image processor settings.
  376. ///
  377. /// - Parameter processor: The processor you want to use to process the image after it is downloaded.
  378. /// - Returns: A `Self` value with changes applied.
  379. ///
  380. /// - Note:
  381. /// To append a processor to current ones instead of replacing them all, use `appendProcessor(_:)`.
  382. public func setProcessor(_ processor: ImageProcessor) -> Self {
  383. options.processor = processor
  384. return self
  385. }
  386. /// Sets an array of image processors for the image task. It replaces the current image processor settings.
  387. /// - Parameter processors: An array of processors. The processors inside this array will be concatenated one by one
  388. /// to form a processor pipeline.
  389. /// - Returns: A `Self` value with changes applied.
  390. ///
  391. /// - Note:
  392. /// To append processors to current ones instead of replacing them all, concatenate them by `|>`, then use
  393. /// `appendProcessor(_:)`.
  394. public func setProcessors(_ processors: [ImageProcessor]) -> Self {
  395. switch processors.count {
  396. case 0:
  397. options.processor = DefaultImageProcessor.default
  398. case 1...:
  399. options.processor = processors.dropFirst().reduce(processors[0]) { $0 |> $1 }
  400. default:
  401. assertionFailure("Never happen")
  402. }
  403. return self
  404. }
  405. /// Appends a processor to the current set processors.
  406. /// - Parameter processor: The processor which will be appended to current processor settings.
  407. /// - Returns: A `Self` value with changes applied.
  408. public func appendProcessor(_ processor: ImageProcessor) -> Self {
  409. options.processor = options.processor |> processor
  410. return self
  411. }
  412. /// Appends a `RoundCornerImageProcessor` to current processors.
  413. /// - Parameters:
  414. /// - radius: The radius will be applied in processing. Specify a certain point value with `.point`, or a fraction
  415. /// of the target image with `.widthFraction`. or `.heightFraction`. For example, given a square image
  416. /// with width and height equals, `.widthFraction(0.5)` means use half of the length of size and makes
  417. /// the final image a round one.
  418. /// - targetSize: Target size of output image should be. If `nil`, the image will keep its original size after processing.
  419. /// - corners: The target corners which will be applied rounding.
  420. /// - backgroundColor: Background color of the output image. If `nil`, it will use a transparent background.
  421. /// - Returns: A `Self` value with changes applied.
  422. public func roundCorner(
  423. radius: RoundCornerImageProcessor.Radius,
  424. targetSize: CGSize? = nil,
  425. roundingCorners corners: RectCorner = .all,
  426. backgroundColor: KFCrossPlatformColor? = nil
  427. ) -> Self
  428. {
  429. let processor = RoundCornerImageProcessor(
  430. radius: radius,
  431. targetSize: targetSize,
  432. roundingCorners: corners,
  433. backgroundColor: backgroundColor
  434. )
  435. return appendProcessor(processor)
  436. }
  437. /// Appends a `BlurImageProcessor` to current processors.
  438. /// - Parameter radius: Blur radius for the simulated Gaussian blur.
  439. /// - Returns: A `Self` value with changes applied.
  440. public func blur(radius: CGFloat) -> Self {
  441. appendProcessor(
  442. BlurImageProcessor(blurRadius: radius)
  443. )
  444. }
  445. /// Appends a `OverlayImageProcessor` to current processors.
  446. /// - Parameters:
  447. /// - color: Overlay color will be used to overlay the input image.
  448. /// - fraction: Fraction will be used when overlay the color to image.
  449. /// - Returns: A `Self` value with changes applied.
  450. public func overlay(color: KFCrossPlatformColor, fraction: CGFloat = 0.5) -> Self {
  451. appendProcessor(
  452. OverlayImageProcessor(overlay: color, fraction: fraction)
  453. )
  454. }
  455. /// Appends a `TintImageProcessor` to current processors.
  456. /// - Parameter color: Tint color will be used to tint the input image.
  457. /// - Returns: A `Self` value with changes applied.
  458. public func tint(color: KFCrossPlatformColor) -> Self {
  459. appendProcessor(
  460. TintImageProcessor(tint: color)
  461. )
  462. }
  463. /// Appends a `BlackWhiteProcessor` to current processors.
  464. /// - Returns: A `Self` value with changes applied.
  465. public func blackWhite() -> Self {
  466. appendProcessor(
  467. BlackWhiteProcessor()
  468. )
  469. }
  470. /// Appends a `CroppingImageProcessor` to current processors.
  471. /// - Parameters:
  472. /// - size: Target size of output image should be.
  473. /// - anchor: Anchor point from which the output size should be calculate. The anchor point is consisted by two
  474. /// values between 0.0 and 1.0. It indicates a related point in current image.
  475. /// See `CroppingImageProcessor.init(size:anchor:)` for more.
  476. /// - Returns: A `Self` value with changes applied.
  477. public func cropping(size: CGSize, anchor: CGPoint = .init(x: 0.5, y: 0.5)) -> Self {
  478. appendProcessor(
  479. CroppingImageProcessor(size: size, anchor: anchor)
  480. )
  481. }
  482. /// Appends a `DownsamplingImageProcessor` to current processors.
  483. ///
  484. /// Compared to `ResizingImageProcessor`, the `DownsamplingImageProcessor` does not render the original images and
  485. /// then resize it. Instead, it downsamples the input data directly to a thumbnail image. So it is a more efficient
  486. /// than `ResizingImageProcessor`. Prefer to use `DownsamplingImageProcessor` as possible
  487. /// as you can than the `ResizingImageProcessor`.
  488. ///
  489. /// Only CG-based images are supported. Animated images (like GIF) is not supported.
  490. ///
  491. /// - Parameter size: Target size of output image should be. It should be smaller than the size of input image.
  492. /// If it is larger, the result image will be the same size of input data without downsampling.
  493. /// - Returns: A `Self` value with changes applied.
  494. public func downsampling(size: CGSize) -> Self {
  495. let processor = DownsamplingImageProcessor(size: size)
  496. if options.processor == DefaultImageProcessor.default {
  497. return setProcessor(processor)
  498. } else {
  499. return appendProcessor(processor)
  500. }
  501. }
  502. /// Appends a `ResizingImageProcessor` to current processors.
  503. ///
  504. /// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
  505. /// instead, which is more efficient and uses less memory.
  506. ///
  507. /// - Parameters:
  508. /// - referenceSize: The reference size for resizing operation in point.
  509. /// - mode: Target content mode of output image should be. Default is `.none`.
  510. /// - Returns: A `Self` value with changes applied.
  511. public func resizing(referenceSize: CGSize, mode: ContentMode = .none) -> Self {
  512. appendProcessor(
  513. ResizingImageProcessor(referenceSize: referenceSize, mode: mode)
  514. )
  515. }
  516. }
  517. // MARK: - Cache Serializer
  518. extension KFOptionSetter {
  519. /// Uses a given `CacheSerializer` to convert some data to an image object for retrieving from disk cache or vice
  520. /// versa for storing to disk cache.
  521. /// - Parameter cacheSerializer: The `CacheSerializer` which will be used.
  522. /// - Returns: A `Self` value with changes applied.
  523. public func serialize(by cacheSerializer: CacheSerializer) -> Self {
  524. options.cacheSerializer = cacheSerializer
  525. return self
  526. }
  527. /// Uses a given format to serializer the image data to disk. It converts the image object to the give data format.
  528. /// - Parameters:
  529. /// - format: The desired data encoding format when store the image on disk.
  530. /// - jpegCompressionQuality: If the format is `.JPEG`, it specify the compression quality when converting the
  531. /// image to a JPEG data. Otherwise, it is ignored.
  532. /// - Returns: A `Self` value with changes applied.
  533. public func serialize(as format: ImageFormat, jpegCompressionQuality: CGFloat? = nil) -> Self {
  534. let cacheSerializer: FormatIndicatedCacheSerializer
  535. switch format {
  536. case .JPEG:
  537. cacheSerializer = .jpeg(compressionQuality: jpegCompressionQuality ?? 1.0)
  538. case .PNG:
  539. cacheSerializer = .png
  540. case .GIF:
  541. cacheSerializer = .gif
  542. case .unknown:
  543. cacheSerializer = .png
  544. }
  545. options.cacheSerializer = cacheSerializer
  546. return self
  547. }
  548. }
  549. // MARK: - Image Modifier
  550. extension KFOptionSetter {
  551. /// Sets an `ImageModifier` to the image task. Use this to modify the fetched image object properties if needed.
  552. ///
  553. /// If the image was fetched directly from the downloader, the modifier will run directly after the
  554. /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
  555. /// - Parameter modifier: The `ImageModifier` which will be used to modify the image object.
  556. /// - Returns: A `Self` value with changes applied.
  557. public func imageModifier(_ modifier: ImageModifier?) -> Self {
  558. options.imageModifier = modifier
  559. return self
  560. }
  561. /// Sets a block to modify the image object. Use this to modify the fetched image object properties if needed.
  562. ///
  563. /// If the image was fetched directly from the downloader, the modifier block will run directly after the
  564. /// `ImageProcessor`. If the image is being fetched from a cache, the modifier will run after the `CacheSerializer`.
  565. ///
  566. /// - Parameter block: The block which is used to modify the image object.
  567. /// - Returns: A `Self` value with changes applied.
  568. public func imageModifier(_ block: @escaping (inout KFCrossPlatformImage) throws -> Void) -> Self {
  569. let modifier = AnyImageModifier { image -> KFCrossPlatformImage in
  570. var image = image
  571. try block(&image)
  572. return image
  573. }
  574. options.imageModifier = modifier
  575. return self
  576. }
  577. }
  578. // MARK: - Cache Expiration
  579. extension KFOptionSetter {
  580. /// Sets the expiration setting for memory cache of this image task.
  581. ///
  582. /// By default, the underlying `MemoryStorage.Backend` uses the
  583. /// expiration in its config for all items. If set, the `MemoryStorage.Backend` will use this value to overwrite
  584. /// the config setting for this caching item.
  585. ///
  586. /// - Parameter expiration: The expiration setting used in cache storage.
  587. /// - Returns: A `Self` value with changes applied.
  588. public func memoryCacheExpiration(_ expiration: StorageExpiration?) -> Self {
  589. options.memoryCacheExpiration = expiration
  590. return self
  591. }
  592. /// Sets the expiration extending setting for memory cache. The item expiration time will be incremented by this
  593. /// value after access.
  594. ///
  595. /// By default, the underlying `MemoryStorage.Backend` uses the initial cache expiration as extending
  596. /// value: .cacheTime.
  597. ///
  598. /// To disable extending option at all, sets `.none` to it.
  599. ///
  600. /// - Parameter extending: The expiration extending setting used in cache storage.
  601. /// - Returns: A `Self` value with changes applied.
  602. public func memoryCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
  603. options.memoryCacheAccessExtendingExpiration = extending
  604. return self
  605. }
  606. /// Sets the expiration setting for disk cache of this image task.
  607. ///
  608. /// By default, the underlying `DiskStorage.Backend` uses the expiration in its config for all items. If set,
  609. /// the `DiskStorage.Backend` will use this value to overwrite the config setting for this caching item.
  610. ///
  611. /// - Parameter expiration: The expiration setting used in cache storage.
  612. /// - Returns: A `Self` value with changes applied.
  613. public func diskCacheExpiration(_ expiration: StorageExpiration?) -> Self {
  614. options.diskCacheExpiration = expiration
  615. return self
  616. }
  617. /// Sets the expiration extending setting for disk cache. The item expiration time will be incremented by this
  618. /// value after access.
  619. ///
  620. /// By default, the underlying `DiskStorage.Backend` uses the initial cache expiration as extending
  621. /// value: .cacheTime.
  622. ///
  623. /// To disable extending option at all, sets `.none` to it.
  624. ///
  625. /// - Parameter extending: The expiration extending setting used in cache storage.
  626. /// - Returns: A `Self` value with changes applied.
  627. public func diskCacheAccessExtending(_ extending: ExpirationExtending) -> Self {
  628. options.diskCacheAccessExtendingExpiration = extending
  629. return self
  630. }
  631. }