KFOptionsSetter.swift 32 KB

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