KFOptionsSetter.swift 33 KB

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