ImageDrawing.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  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. // MARK: Blur
  268. /// Create an image with a blur effect based on the `base` image.
  269. ///
  270. /// - Parameter radius: The blur radius to be used when creating the blur effect.
  271. /// - Returns: An image with the blur effect applied.
  272. ///
  273. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  274. /// > For any non-CG-based image, the `base` image itself is returned.
  275. public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
  276. guard let cgImage = cgImage else {
  277. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  278. return base
  279. }
  280. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  281. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  282. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  283. let s = max(radius, 2.0)
  284. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  285. // Fix the slow compiling time for Swift 3.
  286. // See https://github.com/onevcat/Kingfisher/issues/611
  287. let pi2 = 2 * CGFloat.pi
  288. let sqrtPi2 = sqrt(pi2)
  289. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  290. if targetRadius.isEven { targetRadius += 1 }
  291. // Determine necessary iteration count by blur radius.
  292. let iterations: Int
  293. if radius < 0.5 {
  294. iterations = 1
  295. } else if radius < 1.5 {
  296. iterations = 2
  297. } else {
  298. iterations = 3
  299. }
  300. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  301. let data = context.data
  302. let width = vImagePixelCount(context.width)
  303. let height = vImagePixelCount(context.height)
  304. let rowBytes = context.bytesPerRow
  305. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  306. }
  307. guard let inputContext = CGContext.fresh(cgImage: cgImage) else {
  308. return base
  309. }
  310. inputContext.draw(cgImage, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
  311. var inBuffer = createEffectBuffer(inputContext)
  312. guard let outContext = CGContext.fresh(cgImage: cgImage) else {
  313. return base
  314. }
  315. var outBuffer = createEffectBuffer(outContext)
  316. for _ in 0 ..< iterations {
  317. let flag = vImage_Flags(kvImageEdgeExtend)
  318. vImageBoxConvolve_ARGB8888(
  319. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  320. // Next inBuffer should be the outButter of current iteration
  321. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  322. }
  323. #if os(macOS)
  324. let result = outContext.makeImage().flatMap {
  325. fixedForRetinaPixel(cgImage: $0, to: size)
  326. }
  327. #else
  328. let result = outContext.makeImage().flatMap {
  329. KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  330. }
  331. #endif
  332. guard let blurredImage = result else {
  333. return base
  334. }
  335. return blurredImage
  336. }
  337. public func addingBorder(_ border: Border) -> KFCrossPlatformImage
  338. {
  339. guard let _ = cgImage else {
  340. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  341. return base
  342. }
  343. let rect = CGRect(origin: .zero, size: size)
  344. return draw(to: rect.size, inverting: false) { context in
  345. #if os(macOS)
  346. base.draw(in: rect)
  347. #else
  348. base.draw(in: rect, blendMode: .normal, alpha: 1.0)
  349. #endif
  350. let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2)
  351. context.setStrokeColor(border.color.cgColor)
  352. context.setAlpha(border.color.rgba.a)
  353. let line = pathForRoundCorner(
  354. rect: strokeRect,
  355. radius: border.radius,
  356. corners: border.roundingCorners,
  357. offsetBase: border.lineWidth
  358. )
  359. line.lineCapStyle = .square
  360. line.lineWidth = border.lineWidth
  361. line.stroke()
  362. return false
  363. }
  364. }
  365. // MARK: Overlay
  366. /// Create an image from the `base` image with a color overlay layer.
  367. ///
  368. /// - Parameters:
  369. /// - color: The color to be used for the overlay.
  370. /// - fraction: The fraction of the input color to apply, ranging from 0.0 (solid color) to 1.0 (transparent overlay).
  371. /// - Returns: An image with a color overlay applied.
  372. ///
  373. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  374. /// > For any non-CG-based image, the `base` image itself is returned.
  375. public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
  376. guard let _ = cgImage else {
  377. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  378. return base
  379. }
  380. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  381. return draw(to: rect.size, inverting: false) { context in
  382. #if os(macOS)
  383. base.draw(in: rect)
  384. if fraction > 0 {
  385. color.withAlphaComponent(1 - fraction).set()
  386. rect.fill(using: .sourceAtop)
  387. }
  388. #else
  389. color.set()
  390. UIRectFill(rect)
  391. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  392. if fraction > 0 {
  393. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  394. }
  395. #endif
  396. return false
  397. }
  398. }
  399. // MARK: Tint
  400. /// Create an image from the `base` image with a color tint.
  401. ///
  402. /// - Parameter color: The color to be used for tinting the `base` image.
  403. /// - Returns: An image with a color tint applied.
  404. ///
  405. /// > Important: This method does not work on watchOS, where the original image is returned.
  406. public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
  407. #if os(watchOS)
  408. return base
  409. #else
  410. return apply(.tint(color))
  411. #endif
  412. }
  413. // MARK: Color Control
  414. /// Create an image from `self` with color control adjustments.
  415. ///
  416. /// - Parameters:
  417. /// - brightness: The degree of brightness adjustment to apply to the image.
  418. /// - contrast: The degree of contrast adjustment to apply to the image.
  419. /// - saturation: The degree of saturation adjustment to apply to the image.
  420. /// - inputEV: The exposure value (EV) adjustment to apply to the image.
  421. /// - Returns: An image with color control adjustments applied.
  422. ///
  423. /// > Important: This method does not work on watchOS, where the original image is returned.
  424. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
  425. #if os(watchOS)
  426. return base
  427. #else
  428. let colorElement = Filter.ColorElement(
  429. brightness: brightness,
  430. contrast: contrast,
  431. saturation: saturation,
  432. inputEV: inputEV
  433. )
  434. return apply(.colorControl(colorElement))
  435. #endif
  436. }
  437. /// Return an image with the specified scale.
  438. ///
  439. /// - Parameter scale: The target scale factor for the new image.
  440. /// - Returns: The image with the target scale. If the base image is already at the target scale, the `base` image
  441. /// will be returned.
  442. ///
  443. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  444. /// > For any non-CG-based image, the `base` image itself is returned.
  445. public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
  446. guard scale != self.scale else {
  447. return base
  448. }
  449. guard let cgImage = cgImage else {
  450. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  451. return base
  452. }
  453. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  454. }
  455. }
  456. // MARK: - Decoding Image
  457. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  458. /// Returns the decoded image of the `base` image.
  459. ///
  460. /// On iOS 15 or later, this is identical to the `UIImage.preparingForDisplay` method.
  461. ///
  462. /// In previous versions, this method draws the image in a plain context and returns the data from it. Using this
  463. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  464. /// first time.
  465. ///
  466. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  467. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  468. public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
  469. /// Returns the decoded image of the `base` image at a given `scale`.
  470. ///
  471. /// On iOS 15 or later, this is identical to the `UIImage.preparingForDisplay` method.
  472. ///
  473. /// In previous versions, this method draws the image in a plain context and returns the data from it. Using this
  474. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  475. /// first time.
  476. ///
  477. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  478. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  479. public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
  480. // Prevent animated image (GIF) losing it's images
  481. #if os(iOS) || os(visionOS)
  482. if frameSource != nil { return base }
  483. #else
  484. if images != nil { return base }
  485. #endif
  486. // For older system versions, revert to the drawing for decoding.
  487. guard let imageRef = cgImage else {
  488. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  489. return base
  490. }
  491. #if !os(watchOS) && !os(macOS)
  492. // In newer system versions, use `preparingForDisplay`.
  493. if #available(iOS 15.0, tvOS 15.0, visionOS 1.0, *) {
  494. if base.scale == scale, let image = base.preparingForDisplay() {
  495. return image
  496. }
  497. let scaledImage = KFCrossPlatformImage(cgImage: imageRef, scale: scale, orientation: base.imageOrientation)
  498. if let image = scaledImage.preparingForDisplay() {
  499. return image
  500. }
  501. }
  502. #endif
  503. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  504. return draw(to: size, inverting: true, scale: scale) { context in
  505. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  506. return true
  507. }
  508. }
  509. /// Returns the decoded image of the `base` image on a given `context`.
  510. ///
  511. /// This method draws the image in the given context and returns the data from it. Using this
  512. /// method can improve drawing performance when an image is created from data but hasn't been displayed for the
  513. /// first time.
  514. ///
  515. /// > This method is only applicable to CG-based images. The current image scale is preserved.
  516. /// > For any non-CG-based image or animated image, the `base` image itself is returned.
  517. public func decoded(on context: CGContext) -> KFCrossPlatformImage {
  518. // Prevent animated image (GIF) losing it's images
  519. if frameSource != nil { return base }
  520. guard let refImage = cgImage,
  521. let decodedRefImage = refImage.decoded(on: context, scale: scale) else
  522. {
  523. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  524. return base
  525. }
  526. return KingfisherWrapper.image(cgImage: decodedRefImage, scale: scale, refImage: base)
  527. }
  528. }
  529. extension CGImage {
  530. func decoded(on context: CGContext, scale: CGFloat) -> CGImage? {
  531. let size = CGSize(width: CGFloat(self.width) / scale, height: CGFloat(self.height) / scale)
  532. context.draw(self, in: CGRect(origin: .zero, size: size))
  533. guard let decodedImageRef = context.makeImage() else {
  534. return nil
  535. }
  536. return decodedImageRef
  537. }
  538. static func create(ref: CGImage) -> CGImage? {
  539. guard let space = ref.colorSpace, let provider = ref.dataProvider else {
  540. return nil
  541. }
  542. return CGImage(
  543. width: ref.width,
  544. height: ref.height,
  545. bitsPerComponent: ref.bitsPerComponent,
  546. bitsPerPixel: ref.bitsPerPixel,
  547. bytesPerRow: ref.bytesPerRow,
  548. space: space,
  549. bitmapInfo: ref.bitmapInfo,
  550. provider: provider,
  551. decode: ref.decode,
  552. shouldInterpolate: ref.shouldInterpolate,
  553. intent: ref.renderingIntent
  554. )
  555. }
  556. }
  557. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  558. func draw(
  559. to size: CGSize,
  560. inverting: Bool,
  561. scale: CGFloat? = nil,
  562. refImage: KFCrossPlatformImage? = nil,
  563. draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
  564. ) -> KFCrossPlatformImage
  565. {
  566. #if os(macOS) || os(watchOS)
  567. let targetScale = scale ?? self.scale
  568. GraphicsContext.begin(size: size, scale: targetScale)
  569. guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
  570. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  571. return base
  572. }
  573. defer { GraphicsContext.end() }
  574. let useRefImage = draw(context)
  575. guard let cgImage = context.makeImage() else {
  576. return base
  577. }
  578. let ref = useRefImage ? (refImage ?? base) : nil
  579. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
  580. #else
  581. let format = UIGraphicsImageRendererFormat.preferred()
  582. format.scale = scale ?? self.scale
  583. let renderer = UIGraphicsImageRenderer(size: size, format: format)
  584. var useRefImage: Bool = false
  585. let image = renderer.image { rendererContext in
  586. let context = rendererContext.cgContext
  587. if inverting { // If drawing a CGImage, we need to make context flipped.
  588. context.scaleBy(x: 1.0, y: -1.0)
  589. context.translateBy(x: 0, y: -size.height)
  590. }
  591. useRefImage = draw(context)
  592. }
  593. if useRefImage {
  594. guard let cgImage = image.cgImage else {
  595. return base
  596. }
  597. let ref = refImage ?? base
  598. return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref)
  599. } else {
  600. return image
  601. }
  602. #endif
  603. }
  604. #if os(macOS)
  605. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
  606. let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
  607. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  608. return draw(to: self.size, inverting: false) { context in
  609. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  610. return false
  611. }
  612. }
  613. #endif
  614. }
  615. extension CGContext {
  616. fileprivate static func fresh(cgImage: CGImage) -> CGContext? {
  617. CGContext(
  618. data: nil,
  619. width: cgImage.width,
  620. height: cgImage.height,
  621. bitsPerComponent: 8,
  622. bytesPerRow: 4 * cgImage.width,
  623. space: CGColorSpaceCreateDeviceRGB(),
  624. bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
  625. )
  626. }
  627. }