ImageProcessor.swift 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // ImageProcessor.swift
  3. // Kingfisher
  4. //
  5. // Created by WANG WEI on 2016/08/26.
  6. // Copyright © 2016年 Wei Wang. All rights reserved.
  7. //
  8. import Foundation
  9. import CoreGraphics
  10. public enum ImageProcessItem {
  11. case image(Image)
  12. case data(Data)
  13. }
  14. public protocol ImageProcessor {
  15. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
  16. }
  17. typealias ProcessorImp = ((ImageProcessItem, KingfisherOptionsInfo) -> Image?)
  18. public extension ImageProcessor {
  19. func append(another: ImageProcessor) -> ImageProcessor {
  20. return GeneralProcessor { item, options in
  21. if let image = self.process(item: item, options: options) {
  22. return another.process(item: .image(image), options: options)
  23. } else {
  24. return nil
  25. }
  26. }
  27. }
  28. }
  29. fileprivate struct GeneralProcessor: ImageProcessor {
  30. let p: ProcessorImp
  31. func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  32. return p(item, options)
  33. }
  34. }
  35. public struct DefaultProcessor: ImageProcessor {
  36. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  37. switch item {
  38. case .image(let image):
  39. return image
  40. case .data(let data):
  41. return Image.kf_image(data: data, scale: options.scaleFactor, preloadAllGIFData: options.preloadAllGIFData)
  42. }
  43. }
  44. }
  45. public struct RoundCornerImageProcessor: ImageProcessor {
  46. public let cornerRadius: CGFloat
  47. public let targetSize: CGSize?
  48. public init(cornerRadius: CGFloat, targetSize: CGSize? = nil) {
  49. self.cornerRadius = cornerRadius
  50. self.targetSize = targetSize
  51. }
  52. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  53. switch item {
  54. case .image(let image):
  55. let size = targetSize ?? image.kf_size
  56. return image.kf_image(withRoundRadius: cornerRadius, fit: size, scale: options.scaleFactor)
  57. case .data(_):
  58. return (DefaultProcessor() |> self).process(item: item, options: options)
  59. }
  60. }
  61. }
  62. public struct ResizingImageProcessor: ImageProcessor {
  63. public let targetSize: CGSize
  64. public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
  65. switch item {
  66. case .image(let image):
  67. return image.kf_resize(to: targetSize)
  68. case .data(_):
  69. return (DefaultProcessor() |> self).process(item: item, options: options)
  70. }
  71. }
  72. }
  73. infix operator |>: DefaultPrecedence
  74. public func |>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
  75. return left.append(another: right)
  76. }