ImageDrawing.swift 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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, refRect: rect)
  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, refRect: rect)
  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) -> NSBezierPath {
  169. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
  170. path.windingRule = .evenOdd
  171. return path
  172. }
  173. #else
  174. func pathForRoundCorner(rect: CGRect, radius: Radius, corners: RectCorner, refRect: CGRect) -> UIBezierPath {
  175. let cornerRadius = radius.compute(with: rect.size)
  176. return UIBezierPath(
  177. roundedRect: rect,
  178. byRoundingCorners: corners.uiRectCorner,
  179. cornerRadii: CGSize(width: cornerRadius / (refRect.width / rect.width), height: cornerRadius / (refRect.height / rect.height))
  180. )
  181. }
  182. #endif
  183. #if os(iOS) || os(tvOS)
  184. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> KFCrossPlatformImage {
  185. switch contentMode {
  186. case .scaleAspectFit:
  187. return resize(to: size, for: .aspectFit)
  188. case .scaleAspectFill:
  189. return resize(to: size, for: .aspectFill)
  190. default:
  191. return resize(to: size)
  192. }
  193. }
  194. #endif
  195. // MARK: Resizing
  196. /// Resizes `base` image to an image with new size.
  197. ///
  198. /// - Parameter size: The target size in point.
  199. /// - Returns: An image with new size.
  200. /// - Note: This method only works for CG-based image. The current image scale is kept.
  201. /// For any non-CG-based image, `base` itself is returned.
  202. public func resize(to size: CGSize) -> KFCrossPlatformImage {
  203. guard let _ = cgImage else {
  204. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  205. return base
  206. }
  207. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  208. return draw(to: size, inverting: false) { _ in
  209. #if os(macOS)
  210. base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  211. #else
  212. base.draw(in: rect)
  213. #endif
  214. return false
  215. }
  216. }
  217. /// Resizes `base` image to an image of new size, respecting the given content mode.
  218. ///
  219. /// - Parameters:
  220. /// - targetSize: The target size in point.
  221. /// - contentMode: Content mode of output image should be.
  222. /// - Returns: An image with new size.
  223. ///
  224. /// - Note: This method only works for CG-based image. The current image scale is kept.
  225. /// For any non-CG-based image, `base` itself is returned.
  226. public func resize(to targetSize: CGSize, for contentMode: ContentMode) -> KFCrossPlatformImage {
  227. let newSize = size.kf.resize(to: targetSize, for: contentMode)
  228. return resize(to: newSize)
  229. }
  230. // MARK: Cropping
  231. /// Crops `base` image to a new size with a given anchor.
  232. ///
  233. /// - Parameters:
  234. /// - size: The target size.
  235. /// - anchor: The anchor point from which the size should be calculated.
  236. /// - Returns: An image with new size.
  237. ///
  238. /// - Note: This method only works for CG-based image. The current image scale is kept.
  239. /// For any non-CG-based image, `base` itself is returned.
  240. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> KFCrossPlatformImage {
  241. guard let cgImage = cgImage else {
  242. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  243. return base
  244. }
  245. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  246. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  247. assertionFailure("[Kingfisher] Cropping image failed.")
  248. return base
  249. }
  250. return KingfisherWrapper.image(cgImage: image, scale: scale, refImage: base)
  251. }
  252. // MARK: Blur
  253. /// Creates an image with blur effect based on `base` image.
  254. ///
  255. /// - Parameter radius: The blur radius should be used when creating blur effect.
  256. /// - Returns: An image with blur effect applied.
  257. ///
  258. /// - Note: This method only works for CG-based image. The current image scale is kept.
  259. /// For any non-CG-based image, `base` itself is returned.
  260. public func blurred(withRadius radius: CGFloat) -> KFCrossPlatformImage {
  261. guard let cgImage = cgImage else {
  262. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  263. return base
  264. }
  265. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  266. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  267. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  268. let s = max(radius, 2.0)
  269. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  270. // Fix the slow compiling time for Swift 3.
  271. // See https://github.com/onevcat/Kingfisher/issues/611
  272. let pi2 = 2 * CGFloat.pi
  273. let sqrtPi2 = sqrt(pi2)
  274. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  275. if targetRadius.isEven { targetRadius += 1 }
  276. // Determine necessary iteration count by blur radius.
  277. let iterations: Int
  278. if radius < 0.5 {
  279. iterations = 1
  280. } else if radius < 1.5 {
  281. iterations = 2
  282. } else {
  283. iterations = 3
  284. }
  285. let w = Int(size.width)
  286. let h = Int(size.height)
  287. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  288. let data = context.data
  289. let width = vImagePixelCount(context.width)
  290. let height = vImagePixelCount(context.height)
  291. let rowBytes = context.bytesPerRow
  292. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  293. }
  294. GraphicsContext.begin(size: size, scale: scale)
  295. guard let context = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  296. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  297. return base
  298. }
  299. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  300. GraphicsContext.end()
  301. var inBuffer = createEffectBuffer(context)
  302. GraphicsContext.begin(size: size, scale: scale)
  303. guard let outContext = GraphicsContext.current(size: size, scale: scale, inverting: true, cgImage: cgImage) else {
  304. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  305. return base
  306. }
  307. defer { GraphicsContext.end() }
  308. var outBuffer = createEffectBuffer(outContext)
  309. for _ in 0 ..< iterations {
  310. let flag = vImage_Flags(kvImageEdgeExtend)
  311. vImageBoxConvolve_ARGB8888(
  312. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  313. // Next inBuffer should be the outButter of current iteration
  314. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  315. }
  316. #if os(macOS)
  317. let result = outContext.makeImage().flatMap {
  318. fixedForRetinaPixel(cgImage: $0, to: size)
  319. }
  320. #else
  321. let result = outContext.makeImage().flatMap {
  322. KFCrossPlatformImage(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  323. }
  324. #endif
  325. guard let blurredImage = result else {
  326. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  327. return base
  328. }
  329. return blurredImage
  330. }
  331. public func addingBorder(_ border: Border) -> KFCrossPlatformImage
  332. {
  333. guard let _ = cgImage else {
  334. assertionFailure("[Kingfisher] Blend mode image only works for CG-based image.")
  335. return base
  336. }
  337. let rect = CGRect(origin: .zero, size: size)
  338. return draw(to: rect.size, inverting: false) { context in
  339. base.draw(in: rect, blendMode: .normal, alpha: 1.0)
  340. let strokeRect = rect.insetBy(dx: border.lineWidth / 2, dy: border.lineWidth / 2)
  341. context.setStrokeColor(border.color.cgColor)
  342. let line = pathForRoundCorner(
  343. rect: strokeRect,
  344. radius: border.radius,
  345. corners: border.roundingCorners,
  346. refRect: rect
  347. )
  348. line.lineWidth = border.lineWidth
  349. line.stroke()
  350. return false
  351. }
  352. }
  353. // MARK: Overlay
  354. /// Creates an image from `base` image with a color overlay layer.
  355. ///
  356. /// - Parameters:
  357. /// - color: The color should be use to overlay.
  358. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
  359. /// 1.0 means transparent overlay.
  360. /// - Returns: An image with a color overlay applied.
  361. ///
  362. /// - Note: This method only works for CG-based image. The current image scale is kept.
  363. /// For any non-CG-based image, `base` itself is returned.
  364. public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
  365. guard let _ = cgImage else {
  366. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  367. return base
  368. }
  369. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  370. return draw(to: rect.size, inverting: false) { context in
  371. #if os(macOS)
  372. base.draw(in: rect)
  373. if fraction > 0 {
  374. color.withAlphaComponent(1 - fraction).set()
  375. rect.fill(using: .sourceAtop)
  376. }
  377. #else
  378. color.set()
  379. UIRectFill(rect)
  380. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  381. if fraction > 0 {
  382. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  383. }
  384. #endif
  385. return false
  386. }
  387. }
  388. // MARK: Tint
  389. /// Creates an image from `base` image with a color tint.
  390. ///
  391. /// - Parameter color: The color should be used to tint `base`
  392. /// - Returns: An image with a color tint applied.
  393. public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
  394. #if os(watchOS)
  395. return base
  396. #else
  397. return apply(.tint(color))
  398. #endif
  399. }
  400. // MARK: Color Control
  401. /// Create an image from `self` with color control.
  402. ///
  403. /// - Parameters:
  404. /// - brightness: Brightness changing to image.
  405. /// - contrast: Contrast changing to image.
  406. /// - saturation: Saturation changing to image.
  407. /// - inputEV: InputEV changing to image.
  408. /// - Returns: An image with color control applied.
  409. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
  410. #if os(watchOS)
  411. return base
  412. #else
  413. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  414. #endif
  415. }
  416. /// Return an image with given scale.
  417. ///
  418. /// - Parameter scale: Target scale factor the new image should have.
  419. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  420. public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
  421. guard scale != self.scale else {
  422. return base
  423. }
  424. guard let cgImage = cgImage else {
  425. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  426. return base
  427. }
  428. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  429. }
  430. }
  431. // MARK: - Decoding Image
  432. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  433. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  434. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  435. /// displayed for the first time.
  436. ///
  437. /// - Note: This method only works for CG-based image. The current image scale is kept.
  438. /// For any non-CG-based image or animated image, `base` itself is returned.
  439. public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
  440. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  441. /// return the data from it. This could improve the drawing performance when an image is just created from
  442. /// data but not yet displayed for the first time.
  443. ///
  444. /// - Parameter scale: The given scale of target image should be.
  445. /// - Returns: The decoded image ready to be displayed.
  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 func decoded(scale: CGFloat) -> KFCrossPlatformImage {
  450. // Prevent animated image (GIF) losing it's images
  451. #if os(iOS)
  452. if imageSource != nil { return base }
  453. #else
  454. if images != nil { return base }
  455. #endif
  456. guard let imageRef = cgImage else {
  457. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  458. return base
  459. }
  460. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  461. return draw(to: size, inverting: true, scale: scale) { context in
  462. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  463. return true
  464. }
  465. }
  466. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  467. /// return the data from it. This could improve the drawing performance when an image is just created from
  468. /// data but not yet displayed for the first time.
  469. ///
  470. /// - Parameter context: The context for drawing.
  471. /// - Returns: The decoded image ready to be displayed.
  472. ///
  473. /// - Note: This method only works for CG-based image. The current image scale is kept.
  474. /// For any non-CG-based image or animated image, `base` itself is returned.
  475. public func decoded(on context: CGContext) -> KFCrossPlatformImage {
  476. // Prevent animated image (GIF) losing it's images
  477. #if os(iOS)
  478. if imageSource != nil { return base }
  479. #else
  480. if images != nil { return base }
  481. #endif
  482. guard let refImage = cgImage else {
  483. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  484. return base
  485. }
  486. let size = CGSize(width: CGFloat(refImage.width) / scale, height: CGFloat(refImage.height) / scale)
  487. context.draw(refImage, in: CGRect(origin: .zero, size: size))
  488. guard let cgImage = context.makeImage() else {
  489. return base
  490. }
  491. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  492. }
  493. }
  494. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  495. func draw(
  496. to size: CGSize,
  497. inverting: Bool,
  498. scale: CGFloat? = nil,
  499. refImage: KFCrossPlatformImage? = nil,
  500. draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
  501. ) -> KFCrossPlatformImage
  502. {
  503. #if os(macOS) || os(watchOS)
  504. let targetScale = scale ?? self.scale
  505. GraphicsContext.begin(size: size, scale: targetScale)
  506. guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
  507. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  508. return base
  509. }
  510. defer { GraphicsContext.end() }
  511. let useRefImage = draw(context)
  512. guard let cgImage = context.makeImage() else {
  513. return base
  514. }
  515. let ref = useRefImage ? (refImage ?? base) : nil
  516. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
  517. #else
  518. let format = UIGraphicsImageRendererFormat.default()
  519. format.scale = scale ?? self.scale
  520. let renderer = UIGraphicsImageRenderer(size: size, format: format)
  521. var useRefImage: Bool = false
  522. let image = renderer.image { rendererContext in
  523. let context = rendererContext.cgContext
  524. if inverting { // If drawing a CGImage, we need to make context flipped.
  525. context.scaleBy(x: 1.0, y: -1.0)
  526. context.translateBy(x: 0, y: -size.height)
  527. }
  528. useRefImage = draw(context)
  529. }
  530. if useRefImage {
  531. guard let cgImage = image.cgImage else {
  532. return base
  533. }
  534. let ref = refImage ?? base
  535. return KingfisherWrapper.image(cgImage: cgImage, scale: format.scale, refImage: ref)
  536. } else {
  537. return image
  538. }
  539. #endif
  540. }
  541. #if os(macOS)
  542. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
  543. let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
  544. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  545. return draw(to: self.size, inverting: false) { context in
  546. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  547. return false
  548. }
  549. }
  550. #endif
  551. }