ImageDrawing.swift 23 KB

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