ImageDrawing.swift 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. // MARK: - Image Transforming
  34. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  35. // MARK: Blend Mode
  36. /// Create image from `base` image and apply blend mode.
  37. ///
  38. /// - parameter blendMode: The blend mode of creating image.
  39. /// - parameter alpha: The alpha should be used for image.
  40. /// - parameter backgroundColor: The background color for the output image.
  41. ///
  42. /// - returns: An image with blend mode applied.
  43. ///
  44. /// - Note: This method only works for CG-based image.
  45. #if !os(macOS)
  46. public func image(withBlendMode blendMode: CGBlendMode,
  47. alpha: CGFloat = 1.0,
  48. backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
  49. {
  50. guard let _ = cgImage else {
  51. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  52. return base
  53. }
  54. let rect = CGRect(origin: .zero, size: size)
  55. return draw(to: rect.size, inverting: false) { _ in
  56. if let backgroundColor = backgroundColor {
  57. backgroundColor.setFill()
  58. UIRectFill(rect)
  59. }
  60. base.draw(in: rect, blendMode: blendMode, alpha: alpha)
  61. return false
  62. }
  63. }
  64. #endif
  65. #if os(macOS)
  66. // MARK: Compositing
  67. /// Creates image from `base` image and apply compositing operation.
  68. ///
  69. /// - Parameters:
  70. /// - compositingOperation: The compositing operation of creating image.
  71. /// - alpha: The alpha should be used for image.
  72. /// - backgroundColor: The background color for the output image.
  73. /// - Returns: An image with compositing operation applied.
  74. ///
  75. /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned.
  76. public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
  77. alpha: CGFloat = 1.0,
  78. backgroundColor: KFCrossPlatformColor? = nil) -> KFCrossPlatformImage
  79. {
  80. guard let _ = cgImage else {
  81. assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
  82. return base
  83. }
  84. let rect = CGRect(origin: .zero, size: size)
  85. return draw(to: rect.size, inverting: false) { _ in
  86. if let backgroundColor = backgroundColor {
  87. backgroundColor.setFill()
  88. rect.fill()
  89. }
  90. base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
  91. return false
  92. }
  93. }
  94. #endif
  95. // MARK: Round Corner
  96. /// Creates a round corner image from on `base` image.
  97. ///
  98. /// - Parameters:
  99. /// - radius: The round corner radius of creating image.
  100. /// - size: The target size of creating image.
  101. /// - corners: The target corners which will be applied rounding.
  102. /// - backgroundColor: The background color for the output image
  103. /// - Returns: An image with round corner of `self`.
  104. ///
  105. /// - Note: This method only works for CG-based image. The current image scale is kept.
  106. /// For any non-CG-based image, `base` itself is returned.
  107. public func image(
  108. withRadius radius: Radius,
  109. fit size: CGSize,
  110. roundingCorners corners: RectCorner = .all,
  111. backgroundColor: KFCrossPlatformColor? = nil
  112. ) -> KFCrossPlatformImage
  113. {
  114. guard let _ = cgImage else {
  115. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  116. return base
  117. }
  118. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  119. return draw(to: size, inverting: false) { _ in
  120. #if os(macOS)
  121. if let backgroundColor = backgroundColor {
  122. let rectPath = NSBezierPath(rect: rect)
  123. backgroundColor.setFill()
  124. rectPath.fill()
  125. }
  126. let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
  127. path.addClip()
  128. base.draw(in: rect)
  129. #else
  130. guard let context = UIGraphicsGetCurrentContext() else {
  131. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  132. return false
  133. }
  134. if let backgroundColor = backgroundColor {
  135. let rectPath = UIBezierPath(rect: rect)
  136. backgroundColor.setFill()
  137. rectPath.fill()
  138. }
  139. let path = pathForRoundCorner(rect: rect, radius: radius, corners: corners)
  140. context.addPath(path.cgPath)
  141. context.clip()
  142. base.draw(in: rect)
  143. #endif
  144. return false
  145. }
  146. }
  147. /// Creates a round corner image from on `base` image.
  148. ///
  149. /// - Parameters:
  150. /// - radius: The round corner radius of creating image.
  151. /// - size: The target size of creating image.
  152. /// - corners: The target corners which will be applied rounding.
  153. /// - backgroundColor: The background color for the output image
  154. /// - Returns: An image with round corner of `self`.
  155. ///
  156. /// - Note: This method only works for CG-based image. The current image scale is kept.
  157. /// For any non-CG-based image, `base` itself is returned.
  158. public func image(
  159. withRoundRadius radius: CGFloat,
  160. fit size: CGSize,
  161. roundingCorners corners: RectCorner = .all,
  162. backgroundColor: KFCrossPlatformColor? = nil
  163. ) -> KFCrossPlatformImage
  164. {
  165. image(withRadius: .point(radius), fit: size, roundingCorners: corners, backgroundColor: backgroundColor)
  166. }
  167. #if os(macOS)
  168. func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> NSBezierPath {
  169. let cornerRadius = radius.compute(with: rect.size)
  170. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: cornerRadius - offsetBase / 2)
  171. path.windingRule = .evenOdd
  172. return path
  173. }
  174. #else
  175. func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, offsetBase: CGFloat = 0) -> UIBezierPath {
  176. let cornerRadius = radius.compute(with: rect.size)
  177. return UIBezierPath(
  178. roundedRect: rect,
  179. byRoundingCorners: corners.uiRectCorner,
  180. cornerRadii: CGSize(
  181. width: cornerRadius - offsetBase / 2,
  182. height: cornerRadius - offsetBase / 2
  183. )
  184. )
  185. }
  186. #endif
  187. #if os(iOS) || os(tvOS) || os(visionOS)
  188. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage {
  189. switch contentMode {
  190. case .scaleAspectFit:
  191. return resize(to: size, for: .aspectFit)
  192. case .scaleAspectFill:
  193. return resize(to: size, for: .aspectFill)
  194. default:
  195. return resize(to: size)
  196. }
  197. }
  198. #endif
  199. // MARK: Resizing
  200. /// Resizes `base` image to an image with new size.
  201. ///
  202. /// - Parameter size: The target size in point.
  203. /// - Returns: An image with new size.
  204. /// - Note: This method only works for CG-based image. The current image scale is kept.
  205. /// For any non-CG-based image, `base` itself is returned.
  206. public func resize(to size: CGSize) -> KFCrossPlatformImage {
  207. guard let _ = cgImage else {
  208. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  209. return base
  210. }
  211. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  212. return draw(to: size, inverting: false) { _ in
  213. #if os(macOS)
  214. base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  215. #else
  216. base.draw(in: rect)
  217. #endif
  218. return false
  219. }
  220. }
  221. /// Resizes `base` image to an image of new size, respecting the given content mode.
  222. ///
  223. /// - Parameters:
  224. /// - targetSize: The target size in point.
  225. /// - contentMode: Content mode of output image should be.
  226. /// - Returns: An image with new size.
  227. ///
  228. /// - Note: This method only works for CG-based image. The current image scale is kept.
  229. /// For any non-CG-based image, `base` itself is returned.
  230. public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage {
  231. let newSize = size.kf.resize(to: targetSize, for: contentMode)
  232. return resize(to: newSize)
  233. }
  234. // MARK: Cropping
  235. /// Crops `base` image to a new size with a given anchor.
  236. ///
  237. /// - Parameters:
  238. /// - size: The target size.
  239. /// - anchor: The anchor point from which the size should be calculated.
  240. /// - Returns: An image with new size.
  241. ///
  242. /// - Note: This method only works for CG-based image. The current image scale is kept.
  243. /// For any non-CG-based image, `base` itself is returned.
  244. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage {
  245. guard let cgImage = cgImage else {
  246. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  247. return base
  248. }
  249. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  250. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  251. assertionFailure("[Kingfisher] Cropping image failed.")
  252. return base
  253. }
  254. return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
  255. }
  256. // MARK: Blur
  257. /// Creates an image with blur effect based on `base` image.
  258. ///
  259. /// - Parameter radius: The blur radius should be used when creating blur effect.
  260. /// - Returns: An image with blur effect applied.
  261. ///
  262. /// - Note: This method only works for CG-based image. The current image scale is kept.
  263. /// For any non-CG-based image, `base` itself is returned.
  264. public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
  265. guard let cgImage = cgImage else {
  266. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  267. return base
  268. }
  269. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  270. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  271. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  272. let s = max(radius, 2.0)
  273. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  274. // Fix the slow compiling time for Swift 3.
  275. // See https://github.com/onevcat/Kingfisher/issues/611
  276. let pi2 = 2 * CGFloat.pi
  277. let sqrtPi2 = sqrt(pi2)
  278. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  279. if targetRadius.isEven { targetRadius += 1 }
  280. // Determine necessary iteration count by blur radius.
  281. let iterations: Int
  282. if radius < 0.5 {
  283. iterations = 1
  284. } else if radius < 1.5 {
  285. iterations = 2
  286. } else {
  287. iterations = 3
  288. }
  289. let w = Int(size.width)
  290. let h = Int(size.height)
  291. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  292. let data = context.data
  293. let width = vImagePixelCount(context.width)
  294. let height = vImagePixelCount(context.height)
  295. let rowBytes = context.bytesPerRow
  296. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  297. }
  298. GraphicsContext.begin(size: size, scale: scale)
  299. guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  300. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  301. return base
  302. }
  303. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  304. GraphicsContext.end()
  305. var inBuffer = createEffectBuffer(context)
  306. GraphicsContext.begin(size: size, scale: scale)
  307. guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  308. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  309. return base
  310. }
  311. defer { GraphicsContext.end() }
  312. var outBuffer = createEffectBuffer(outContext)
  313. for _ in 0 ..< iterations {
  314. let flag = vImage_Flags(kvImageEdgeExtend)
  315. vImageBoxConvolve_ARGB8888(
  316. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  317. // Next inBuffer should be the outButter of current iteration
  318. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  319. }
  320. #if os(macOS)
  321. let result = outContext.makeImage().flatMap {
  322. fixedForRetinaPixel(cgImage: $0, to: size)
  323. }
  324. #else
  325. let result = outContext.makeImage().flatMap {
  326. KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  327. }
  328. #endif
  329. guard let blurredImage = result else {
  330. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  331. return base
  332. }
  333. return blurredImage
  334. }
  335. public func addingBorder(_ border: Border) -> KFCrossPlatformImage
  336. {
  337. guard let _ = cgImage else {
  338. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  339. return base
  340. }
  341. let rect = CGRect(origin: .zero, size: size)
  342. return draw(to: rect.size, inverting: false) { context in
  343. #if os(macOS)
  344. base.draw(in: rect)
  345. #else
  346. base.draw(in: rect, blendMode: .normal, alpha: 1.0)
  347. #endif
  348. let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2)
  349. context.setStrokeColor(border.color.cgColor)
  350. context.setAlpha(border.color.rgba.a)
  351. let line = pathForRoundCorner(
  352. rect: strokeRect,
  353. radius: border.radius,
  354. corners: border.roundingCorners,
  355. offsetBase: border.lineWidth
  356. )
  357. line.lineCapStyle = .square
  358. line.lineWidth = border.lineWidth
  359. line.stroke()
  360. return false
  361. }
  362. }
  363. // MARK: Overlay
  364. /// Creates an image from `base` image with a color overlay layer.
  365. ///
  366. /// - Parameters:
  367. /// - color: The color should be use to overlay.
  368. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
  369. /// 1.0 means transparent overlay.
  370. /// - Returns: An image with a color overlay applied.
  371. ///
  372. /// - Note: This method only works for CG-based image. The current image scale is kept.
  373. /// For any non-CG-based image, `base` itself is returned.
  374. public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
  375. guard let _ = cgImage else {
  376. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  377. return base
  378. }
  379. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  380. return draw(to: rect.size, inverting: false) { context in
  381. #if os(macOS)
  382. base.draw(in: rect)
  383. if fraction > 0 {
  384. color.withAlphaComponent(1 - fraction).set()
  385. rect.fill(using: .sourceAtop)
  386. }
  387. #else
  388. color.set()
  389. UIRectFill(rect)
  390. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  391. if fraction > 0 {
  392. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  393. }
  394. #endif
  395. return false
  396. }
  397. }
  398. // MARK: Tint
  399. /// Creates an image from `base` image with a color tint.
  400. ///
  401. /// - Parameter color: The color should be used to tint `base`
  402. /// - Returns: An image with a color tint applied.
  403. public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
  404. #if os(watchOS)
  405. return base
  406. #else
  407. return apply(.tint(color))
  408. #endif
  409. }
  410. // MARK: Color Control
  411. /// Create an image from `self` with color control.
  412. ///
  413. /// - Parameters:
  414. /// - brightness: Brightness changing to image.
  415. /// - contrast: Contrast changing to image.
  416. /// - saturation: Saturation changing to image.
  417. /// - inputEV: InputEV changing to image.
  418. /// - Returns: An image with color control applied.
  419. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
  420. #if os(watchOS)
  421. return base
  422. #else
  423. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  424. #endif
  425. }
  426. /// Return an image with given scale.
  427. ///
  428. /// - Parameter scale: Target scale factor the new image should have.
  429. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  430. public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
  431. guard scale != self.scale else {
  432. return base
  433. }
  434. guard let cgImage = cgImage else {
  435. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  436. return base
  437. }
  438. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  439. }
  440. }
  441. // MARK: - Decoding Image
  442. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  443. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  444. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  445. /// displayed for the first time.
  446. ///
  447. /// - Note: This method only works for CG-based image. The current image scale is kept.
  448. /// For any non-CG-based image or animated image, `base` itself is returned.
  449. public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
  450. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  451. /// return the data from it. This could improve the drawing performance when an image is just created from
  452. /// data but not yet displayed for the first time.
  453. ///
  454. /// - Parameter scale: The given scale of target image should be.
  455. /// - Returns: The decoded image ready to be displayed.
  456. ///
  457. /// - Note: This method only works for CG-based image. The current image scale is kept.
  458. /// For any non-CG-based image or animated image, `base` itself is returned.
  459. public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
  460. // Prevent animated image (GIF) losing it's images
  461. #if os(iOS) || os(visionOS)
  462. if frameSource != nil { return base }
  463. #else
  464. if images != nil { return base }
  465. #endif
  466. guard let imageRef = cgImage else {
  467. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  468. return base
  469. }
  470. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  471. return draw(to: size, inverting: true, scale: scale) { context in
  472. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  473. return true
  474. }
  475. }
  476. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  477. /// return the data from it. This could improve the drawing performance when an image is just created from
  478. /// data but not yet displayed for the first time.
  479. ///
  480. /// - Parameter context: The context for drawing.
  481. /// - Returns: The decoded image ready to be displayed.
  482. ///
  483. /// - Note: This method only works for CG-based image. The current image scale is kept.
  484. /// For any non-CG-based image or animated image, `base` itself is returned.
  485. public func decoded(on context: CGContext) -> KFCrossPlatformImage {
  486. // Prevent animated image (GIF) losing it's images
  487. #if os(iOS) || os(visionOS)
  488. if frameSource != nil { return base }
  489. #else
  490. if images != nil { return base }
  491. #endif
  492. guard let refImage = cgImage,
  493. let decodedRefImage = refImage.decoded(on: context, scale: scale) else
  494. {
  495. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  496. return base
  497. }
  498. return KingfisherWrapper.image(cgImage: decodedRefImage, scale: scale, refImage: base)
  499. }
  500. }
  501. extension CGImage {
  502. func decoded(on context: CGContext, scale: CGFloat) -> CGImage? {
  503. let size = CGSize(width: CGFloat(self.width) / scale, height: CGFloat(self.height) / scale)
  504. context.draw(self, in: CGRect(origin: .zero, size: size))
  505. guard let decodedImageRef = context.makeImage() else {
  506. return nil
  507. }
  508. return decodedImageRef
  509. }
  510. }
  511. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  512. func draw(
  513. to size: CGSize,
  514. inverting: Bool,
  515. scale: CGFloat? = nil,
  516. refImage: KFCrossPlatformImage? = nil,
  517. draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
  518. ) -> KFCrossPlatformImage
  519. {
  520. #if os(macOS) || os(watchOS)
  521. let targetScale = scale ?? self.scale
  522. GraphicsContext.begin(size: size, scale: targetScale)
  523. guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
  524. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  525. return base
  526. }
  527. defer { GraphicsContext.end() }
  528. let useRefImage = draw(context)
  529. guard let cgImage = context.makeImage() else {
  530. return base
  531. }
  532. let ref = useRefImage ? (refImage ?? base) : nil
  533. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
  534. #else
  535. let format = UIGraphicsImageRendererFormat.preferred()
  536. format.scale = scale ?? self.scale
  537. let renderer = UIGraphicsImageRenderer(size: size, format: format)
  538. var useRefImage: Bool = false
  539. let image = renderer.image { rendererContext in
  540. let context = rendererContext.cgContext
  541. if inverting { // If drawing a CGImage, we need to make context flipped.
  542. context.scaleBy(x: 1.0, y: -1.0)
  543. context.translateBy(x: 0, y: -size.height)
  544. }
  545. useRefImage = draw(context)
  546. }
  547. if useRefImage {
  548. guard let cgImage = image.cgImage else {
  549. return base
  550. }
  551. let ref = refImage ?? base
  552. return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref)
  553. } else {
  554. return image
  555. }
  556. #endif
  557. }
  558. #if os(macOS)
  559. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
  560. let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
  561. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  562. return draw(to: self.size, inverting: false) { context in
  563. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  564. return false
  565. }
  566. }
  567. #endif
  568. }