ImageDrawing.swift 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  1. //
  2. // ImageDrawing.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/09/28.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Accelerate
  27. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  28. import AppKit
  29. #endif
  30. #if canImport(UIKit)
  31. import UIKit
  32. #endif
  33. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  34. // MARK: - Image Transforming
  35. // MARK: Blend Mode
  36. #if !os(macOS)
  37. /// Create an image from the `base` image and apply a blend mode.
  38. ///
  39. /// - Parameters:
  40. /// - blendMode: The blend mode to be applied to the image.
  41. /// - alpha: The alpha value to be used for the image.
  42. /// - backgroundColor: The background color for the output image.
  43. /// - Returns: An image with the specified blend mode applied.
  44. ///
  45. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  46. /// > For any non-CG-based image, the `base` image itself is returned.
  47. public func image(withBlendMode blendMode: CGBlendMode,
  48. alpha: CGFloat = 1.0,
  49. backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
  50. {
  51. guard let _ = cgImage else {
  52. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  53. return base
  54. }
  55. let rect = CGRect(origin: .zero, size: size)
  56. return draw(to: rect.size, inverting: false) { _ in
  57. if let backgroundColor = backgroundColor {
  58. backgroundColor.setFill()
  59. UIRectFill(rect)
  60. }
  61. base.draw(in: rect, blendMode: blendMode, alpha: alpha)
  62. return false
  63. }
  64. }
  65. #endif
  66. #if os(macOS)
  67. // MARK: Compositing
  68. /// Create an image from the `base` image and apply a compositing operation.
  69. ///
  70. /// - Parameters:
  71. /// - compositingOperation: The compositing operation to be applied to the image.
  72. /// - alpha: The alpha value to be used for the image.
  73. /// - backgroundColor: The background color for the output image.
  74. /// - Returns: An image with the specified compositing operation applied.
  75. ///
  76. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  77. /// > For any non-CG-based image, the `base` image itself is returned.
  78. public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
  79. alpha: CGFloat = 1.0,
  80. backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
  81. {
  82. guard let _ = cgImage else {
  83. assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
  84. return base
  85. }
  86. let rect = CGRect(origin: .zero, size: size)
  87. return draw(to: rect.size, inverting: false) { _ in
  88. if let backgroundColor = backgroundColor {
  89. backgroundColor.setFill()
  90. rect.fill()
  91. }
  92. base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
  93. return false
  94. }
  95. }
  96. #endif
  97. // MARK: Round Corner
  98. /// Create a rounded corner image from the `base` image.
  99. ///
  100. /// - Parameters:
  101. /// - radius: The radius for rounding the corners of the image.
  102. /// - size: The target size of the resulting image.
  103. /// - corners: The corners to which rounding will be applied.
  104. /// - backgroundColor: The background color for the output image.
  105. /// - Returns: An image with rounded corners based on `self`.
  106. ///
  107. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  108. /// > For any non-CG-based image, the `base` image itself is returned.
  109. public func image(
  110. withRadius radius: Radius,
  111. fit size: CGSize,
  112. roundingCorners corners: RectCorner = .all,
  113. backgroundColor: KFCrossPlatformColor? = nil
  114. ) -> KFCrossPlatformImage
  115. {
  116. guard let _ = cgImage else {
  117. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  118. return base
  119. }
  120. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  121. return draw(to: size, inverting: false) { _ in
  122. #if os(macOS)
  123. if let backgroundColor = backgroundColor {
  124. let rectPath = NSBezierPath(rect: rect)
  125. backgroundColor.setFill()
  126. rectPath.fill()
  127. }
  128. let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
  129. path.addClip()
  130. base.draw(in: rect)
  131. #else
  132. guard let context = UIGraphicsGetCurrentContext() else {
  133. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  134. return false
  135. }
  136. if let backgroundColor = backgroundColor {
  137. let rectPath = UIBezierPath(rect: rect)
  138. backgroundColor.setFill()
  139. rectPath.fill()
  140. }
  141. let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
  142. context.addPath(path.cgPath)
  143. context.clip()
  144. base.draw(in: rect)
  145. #endif
  146. return false
  147. }
  148. }
  149. /// Create a round corner image from the `base` image.
  150. ///
  151. /// - Parameters:
  152. /// - radius: The radius for rounding the corners of the image.
  153. /// - size: The target size of the resulting image.
  154. /// - corners: The corners to which rounding will be applied.
  155. /// - backgroundColor: The background color for the output image.
  156. /// - Returns: An image with rounded corners based on `self`.
  157. ///
  158. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  159. /// > For any non-CG-based image, the `base` image itself is returned.
  160. public func image(
  161. withRoundRadius radius: CGFloat,
  162. fit size: CGSize,
  163. roundingCorners corners: RectCorner = .all,
  164. backgroundColor: KFCrossPlatformColor? = nil
  165. ) -> KFCrossPlatformImage
  166. {
  167. image(withRadius: .point(radius), fit: size, roundingCorners: corners, backgroundColor: backgroundColor)
  168. }
  169. #if os(macOS)
  170. func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> NSBezierPath {
  171. let cornerRadius = radius.compute(with: rect.size)
  172. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: cornerRadius - offsetBase / 2)
  173. path.windingRule = .evenOdd
  174. return path
  175. }
  176. #else
  177. func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> UIBezierPath {
  178. let cornerRadius = radius.compute(with: rect.size)
  179. return UIBezierPath(
  180. roundedRect: rect,
  181. byRoundingCorners: corners.uiRectCorner,
  182. cornerRadii: CGSize(
  183. width: cornerRadius - offsetBase / 2,
  184. height: cornerRadius - offsetBase / 2
  185. )
  186. )
  187. }
  188. #endif
  189. #if os(iOS) || os(tvOS) || os(visionOS)
  190. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage {
  191. switch contentMode {
  192. case .scaleAspectFit:
  193. return resize(to: size, for: .aspectFit)
  194. case .scaleAspectFill:
  195. return resize(to: size, for: .aspectFill)
  196. default:
  197. return resize(to: size)
  198. }
  199. }
  200. #endif
  201. // MARK: Resizing
  202. /// Resize the `base` image to a new size.
  203. ///
  204. /// - Parameter size: The target size in points.
  205. /// - Returns: An image with the new size.
  206. ///
  207. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  208. /// > For any non-CG-based image, the `base` image itself is returned.
  209. ///
  210. /// > Tip: This method resizes the `base` image to a specified size by drawing it into that size. If you require a
  211. /// smaller thumbnail of the image, consider using ``downsampledImage(data:to:scale:)`` instead, as it offers
  212. /// improved efficiency.
  213. public func resize(to size: CGSize) -> KFCrossPlatformImage {
  214. guard let _ = cgImage else {
  215. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  216. return base
  217. }
  218. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  219. return draw(to: size, inverting: false) { _ in
  220. #if os(macOS)
  221. base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  222. #else
  223. base.draw(in: rect)
  224. #endif
  225. return false
  226. }
  227. }
  228. /// Resize the `base` image to a new size while respecting the specified content mode.
  229. ///
  230. /// - Parameters:
  231. /// - targetSize: The target size in points.
  232. /// - contentMode: The desired content mode for the output image.
  233. /// - Returns: An image with the new size.
  234. ///
  235. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  236. /// > For any non-CG-based image, the `base` image itself is returned.
  237. ///
  238. /// > Tip: This method resizes the `base` image to a specified size by drawing it into that size. If you require a
  239. /// smaller thumbnail of the image, consider using ``downsampledImage(data:to:scale:)`` instead, as it offers
  240. /// improved efficiency.
  241. public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage {
  242. let newSize = size.kf.resize(to: targetSize, for: contentMode)
  243. return resize(to: newSize)
  244. }
  245. // MARK: Cropping
  246. /// Crop the `base` image to a new size with a specified anchor point.
  247. ///
  248. /// - Parameters:
  249. /// - size: The target size.
  250. /// - anchor: The anchor point from which the size should be calculated.
  251. /// - Returns: An image with the new size.
  252. ///
  253. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  254. /// > For any non-CG-based image, the `base` image itself is returned.
  255. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage {
  256. guard let cgImage = cgImage else {
  257. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  258. return base
  259. }
  260. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  261. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  262. assertionFailure("[Kingfisher] Cropping image failed.")
  263. return base
  264. }
  265. return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
  266. }
  267. public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
  268. guard let cgImage = cgImage, let colorSpace = cgImage.colorSpace else {
  269. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  270. return base
  271. }
  272. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  273. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  274. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  275. let s = max(radius, 2.0)
  276. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  277. // Fix the slow compiling time for Swift 3.
  278. // See https://github.com/onevcat/Kingfisher/issues/611
  279. let pi2 = 2 * CGFloat.pi
  280. let sqrtPi2 = sqrt(pi2)
  281. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  282. if targetRadius.isEven { targetRadius += 1 }
  283. // Determine necessary iteration count by blur radius.
  284. let iterations: Int
  285. if radius < 0.5 {
  286. iterations = 1
  287. } else if radius < 1.5 {
  288. iterations = 2
  289. } else {
  290. iterations = 3
  291. }
  292. let inProvider = cgImage.dataProvider
  293. let width = vImagePixelCount(cgImage.width)
  294. let height = vImagePixelCount(cgImage.height)
  295. let rowBytes = cgImage.bytesPerRow
  296. let inBitmapData = inProvider?.data
  297. let inData = UnsafeMutableRawPointer(mutating: CFDataGetBytePtr(inBitmapData))
  298. var inBuffer = vImage_Buffer(data: inData, height: height, width: width, rowBytes: rowBytes)
  299. let outData = malloc(cgImage.bytesPerRow * cgImage.height)
  300. var outBuffer = vImage_Buffer(data: outData, height: height, width: width, rowBytes: rowBytes)
  301. for _ in 0 ..< iterations {
  302. let flag = vImage_Flags(kvImageEdgeExtend)
  303. vImageBoxConvolve_ARGB8888(
  304. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  305. // Next inBuffer should be the outButter of current iteration
  306. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  307. }
  308. let outContext = CGContext(
  309. data: outBuffer.data,
  310. width: Int(outBuffer.width),
  311. height: Int(outBuffer.height),
  312. bitsPerComponent: 8,
  313. bytesPerRow: outBuffer.rowBytes,
  314. space: colorSpace,
  315. bitmapInfo: cgImage.bitmapInfo.rawValue
  316. )
  317. let result = outContext?.makeImage().flatMap {
  318. KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  319. }
  320. guard let blurredImage = result else {
  321. return base
  322. }
  323. return blurredImage
  324. }
  325. // MARK: Blur
  326. /// Create an image with a blur effect based on the `base` image.
  327. ///
  328. /// - Parameter radius: The blur radius to be used when creating the blur effect.
  329. /// - Returns: An image with the blur effect applied.
  330. ///
  331. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  332. /// > For any non-CG-based image, the `base` image itself is returned.
  333. public func blurredOld(withRadius radius: CGFloat) -> KFCrossPlatformImage {
  334. guard let cgImage = cgImage else {
  335. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  336. return base
  337. }
  338. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  339. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  340. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  341. let s = max(radius, 2.0)
  342. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  343. // Fix the slow compiling time for Swift 3.
  344. // See https://github.com/onevcat/Kingfisher/issues/611
  345. let pi2 = 2 * CGFloat.pi
  346. let sqrtPi2 = sqrt(pi2)
  347. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  348. if targetRadius.isEven { targetRadius += 1 }
  349. // Determine necessary iteration count by blur radius.
  350. let iterations: Int
  351. if radius < 0.5 {
  352. iterations = 1
  353. } else if radius < 1.5 {
  354. iterations = 2
  355. } else {
  356. iterations = 3
  357. }
  358. let w = Int(size.width)
  359. let h = Int(size.height)
  360. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  361. let data = context.data
  362. let width = vImagePixelCount(context.width)
  363. let height = vImagePixelCount(context.height)
  364. let rowBytes = context.bytesPerRow
  365. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  366. }
  367. GraphicsContext.begin(size: size, scale: scale)
  368. guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  369. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  370. return base
  371. }
  372. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  373. GraphicsContext.end()
  374. var inBuffer = createEffectBuffer(context)
  375. GraphicsContext.begin(size: size, scale: scale)
  376. guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  377. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  378. return base
  379. }
  380. defer { GraphicsContext.end() }
  381. var outBuffer = createEffectBuffer(outContext)
  382. for _ in 0 ..< iterations {
  383. let flag = vImage_Flags(kvImageEdgeExtend)
  384. vImageBoxConvolve_ARGB8888(
  385. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  386. // Next inBuffer should be the outButter of current iteration
  387. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  388. }
  389. #if os(macOS)
  390. let result = outContext.makeImage().flatMap {
  391. fixedForRetinaPixel(cgImage: $0, to: size)
  392. }
  393. #else
  394. let result = outContext.makeImage().flatMap {
  395. KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  396. }
  397. #endif
  398. guard let blurredImage = result else {
  399. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  400. return base
  401. }
  402. return blurredImage
  403. }
  404. public func addingBorder(_ border: Border) -> KFCrossPlatformImage
  405. {
  406. guard let _ = cgImage else {
  407. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  408. return base
  409. }
  410. let rect = CGRect(origin: .zero, size: size)
  411. return draw(to: rect.size, inverting: false) { context in
  412. #if os(macOS)
  413. base.draw(in: rect)
  414. #else
  415. base.draw(in: rect, blendMode: .normal, alpha: 1.0)
  416. #endif
  417. let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2)
  418. context.setStrokeColor(border.color.cgColor)
  419. context.setAlpha(border.color.rgba.a)
  420. let line = pathForRoundCorner(
  421. rect: strokeRect,
  422. radius: border.radius,
  423. corners: border.roundingCorners,
  424. offsetBase: border.lineWidth
  425. )
  426. line.lineCapStyle = .square
  427. line.lineWidth = border.lineWidth
  428. line.stroke()
  429. return false
  430. }
  431. }
  432. // MARK: Overlay
  433. /// Create an image from the `base` image with a color overlay layer.
  434. ///
  435. /// - Parameters:
  436. /// - color: The color to be used for the overlay.
  437. /// - fraction: The fraction of the input color to apply, ranging from 0.0 (solid color) to 1.0 (transparent overlay).
  438. /// - Returns: An image with a color overlay applied.
  439. ///
  440. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  441. /// > For any non-CG-based image, the `base` image itself is returned.
  442. public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
  443. guard let _ = cgImage else {
  444. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  445. return base
  446. }
  447. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  448. return draw(to: rect.size, inverting: false) { context in
  449. #if os(macOS)
  450. base.draw(in: rect)
  451. if fraction > 0 {
  452. color.withAlphaComponent(1 - fraction).set()
  453. rect.fill(using: .sourceAtop)
  454. }
  455. #else
  456. color.set()
  457. UIRectFill(rect)
  458. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  459. if fraction > 0 {
  460. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  461. }
  462. #endif
  463. return false
  464. }
  465. }
  466. // MARK: Tint
  467. /// Create an image from the `base` image with a color tint.
  468. ///
  469. /// - Parameter color: The color to be used for tinting the `base` image.
  470. /// - Returns: An image with a color tint applied.
  471. ///
  472. /// > Important: This method does not work on watchOS, where the original image is returned.
  473. public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
  474. #if os(watchOS)
  475. return base
  476. #else
  477. return apply(.tint(color))
  478. #endif
  479. }
  480. // MARK: Color Control
  481. /// Create an image from `self` with color control adjustments.
  482. ///
  483. /// - Parameters:
  484. /// - brightness: The degree of brightness adjustment to apply to the image.
  485. /// - contrast: The degree of contrast adjustment to apply to the image.
  486. /// - saturation: The degree of saturation adjustment to apply to the image.
  487. /// - inputEV: The exposure value (EV) adjustment to apply to the image.
  488. /// - Returns: An image with color control adjustments applied.
  489. ///
  490. /// > Important: This method does not work on watchOS, where the original image is returned.
  491. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
  492. #if os(watchOS)
  493. return base
  494. #else
  495. let colorElement = Filter.ColorElement(
  496. brightness: brightness,
  497. contrast: contrast,
  498. saturation: saturation,
  499. inputEV: inputEV
  500. )
  501. return apply(.colorControl(colorElement))
  502. #endif
  503. }
  504. /// Return an image with the specified scale.
  505. ///
  506. /// - Parameter scale: The target scale factor for the new image.
  507. /// - Returns: The image with the target scale. If the base image is already at the target scale, the `base` image
  508. /// will be returned.
  509. ///
  510. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  511. /// > For any non-CG-based image, the `base` image itself is returned.
  512. public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
  513. guard scale != self.scale else {
  514. return base
  515. }
  516. guard let cgImage = cgImage else {
  517. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  518. return base
  519. }
  520. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  521. }
  522. }
  523. // MARK: - Decoding Image
  524. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  525. /// Returns the decoded image of the `base` image.
  526. ///
  527. /// On iOS 15 or later, this is identical to the `UIImage.preparingForDisplay` method.
  528. ///
  529. /// In previous versions, this method draws the image in a plain context and returns the data from it. Using this
  530. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  531. /// first time.
  532. ///
  533. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  534. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  535. public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
  536. /// Returns the decoded image of the `base` image at a given `scale`.
  537. ///
  538. /// On iOS 15 or later, this is identical to the `UIImage.preparingForDisplay` method.
  539. ///
  540. /// In previous versions, this method draws the image in a plain context and returns the data from it. Using this
  541. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  542. /// first time.
  543. ///
  544. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  545. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  546. public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
  547. // Prevent animated image (GIF) losing it's images
  548. #if os(iOS) || os(visionOS)
  549. if frameSource != nil { return base }
  550. #else
  551. if images != nil { return base }
  552. #endif
  553. // For older system versions, revert to the drawing for decoding.
  554. guard let imageRef = cgImage else {
  555. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  556. return base
  557. }
  558. #if !os(watchOS) && !os(macOS)
  559. // In newer system versions, use `preparingForDisplay`.
  560. if #available(iOS 15.0, tvOS 15.0, visionOS 1.0, *) {
  561. if base.scale == scale, let image = base.preparingForDisplay() {
  562. return image
  563. }
  564. let scaledImage = KFCrossPlatformImage(cgImage: imageRef, scale: scale, orientation: base.imageOrientation)
  565. if let image = scaledImage.preparingForDisplay() {
  566. return image
  567. }
  568. }
  569. #endif
  570. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  571. return draw(to: size, inverting: true, scale: scale) { context in
  572. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  573. return true
  574. }
  575. }
  576. /// Returns the decoded image of the `base` image on a given `context`.
  577. ///
  578. /// This method draws the image in the given context and returns the data from it. Using this
  579. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  580. /// first time.
  581. ///
  582. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  583. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  584. public func decoded(on context: CGContext) -> KFCrossPlatformImage {
  585. // Prevent animated image (GIF) losing it's images
  586. if frameSource != nil { return base }
  587. guard let refImage = cgImage,
  588. let decodedRefImage = refImage.decoded(on: context, scale: scale) else
  589. {
  590. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  591. return base
  592. }
  593. return KingfisherWrapper.image(cgImage: decodedRefImage, scale: scale, refImage: base)
  594. }
  595. }
  596. extension CGImage {
  597. func decoded(on context: CGContext, scale: CGFloat) -> CGImage? {
  598. let size = CGSize(width: CGFloat(self.width) / scale, height: CGFloat(self.height) / scale)
  599. context.draw(self, in: CGRect(origin: .zero, size: size))
  600. guard let decodedImageRef = context.makeImage() else {
  601. return nil
  602. }
  603. return decodedImageRef
  604. }
  605. static func create(ref: CGImage) -> CGImage? {
  606. guard let space = ref.colorSpace, let provider = ref.dataProvider else {
  607. return nil
  608. }
  609. return CGImage(
  610. width: ref.width,
  611. height: ref.height,
  612. bitsPerComponent: ref.bitsPerComponent,
  613. bitsPerPixel: ref.bitsPerPixel,
  614. bytesPerRow: ref.bytesPerRow,
  615. space: space,
  616. bitmapInfo: ref.bitmapInfo,
  617. provider: provider,
  618. decode: ref.decode,
  619. shouldInterpolate: ref.shouldInterpolate,
  620. intent: ref.renderingIntent
  621. )
  622. }
  623. }
  624. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  625. func draw(
  626. to size: CGSize,
  627. inverting: Bool,
  628. scale: CGFloat? = nil,
  629. refImage: KFCrossPlatformImage? = nil,
  630. draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
  631. ) -> KFCrossPlatformImage
  632. {
  633. #if os(macOS) || os(watchOS)
  634. let targetScale = scale ?? self.scale
  635. GraphicsContext.begin(size: size, scale: targetScale)
  636. guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
  637. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  638. return base
  639. }
  640. defer { GraphicsContext.end() }
  641. let useRefImage = draw(context)
  642. guard let cgImage = context.makeImage() else {
  643. return base
  644. }
  645. let ref = useRefImage ? (refImage ?? base) : nil
  646. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
  647. #else
  648. let format = UIGraphicsImageRendererFormat.preferred()
  649. format.scale = scale ?? self.scale
  650. let renderer = UIGraphicsImageRenderer(size: size, format: format)
  651. var useRefImage: Bool = false
  652. let image = renderer.image { rendererContext in
  653. let context = rendererContext.cgContext
  654. if inverting { // If drawing a CGImage, we need to make context flipped.
  655. context.scaleBy(x: 1.0, y: -1.0)
  656. context.translateBy(x: 0, y: -size.height)
  657. }
  658. useRefImage = draw(context)
  659. }
  660. if useRefImage {
  661. guard let cgImage = image.cgImage else {
  662. return base
  663. }
  664. let ref = refImage ?? base
  665. return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref)
  666. } else {
  667. return image
  668. }
  669. #endif
  670. }
  671. #if os(macOS)
  672. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
  673. let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
  674. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  675. return draw(to: self.size, inverting: false) { context in
  676. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  677. return false
  678. }
  679. }
  680. #endif
  681. }