ImageDrawing.swift 25 KB

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