2
0

ImageDrawing.swift 28 KB

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