ImageDrawing.swift 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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) { _ 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) { _ 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) { _ 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) { _ 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. // MARK: Overlay
  299. /// Creates an image from `base` image with a color overlay layer.
  300. ///
  301. /// - Parameters:
  302. /// - color: The color should be use to overlay.
  303. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
  304. /// 1.0 means transparent overlay.
  305. /// - Returns: An image with a color overlay applied.
  306. ///
  307. /// - Note: This method only works for CG-based image. The current image scale is kept.
  308. /// For any non-CG-based image, `base` itself is returned.
  309. public func overlaying(with color: KFCrossPlatformColor, fraction: CGFloat) -> KFCrossPlatformImage {
  310. guard let _ = cgImage else {
  311. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  312. return base
  313. }
  314. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  315. return draw(to: rect.size) { context in
  316. #if os(macOS)
  317. base.draw(in: rect)
  318. if fraction > 0 {
  319. color.withAlphaComponent(1 - fraction).set()
  320. rect.fill(using: .sourceAtop)
  321. }
  322. #else
  323. color.set()
  324. UIRectFill(rect)
  325. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  326. if fraction > 0 {
  327. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  328. }
  329. #endif
  330. return false
  331. }
  332. }
  333. // MARK: Tint
  334. /// Creates an image from `base` image with a color tint.
  335. ///
  336. /// - Parameter color: The color should be used to tint `base`
  337. /// - Returns: An image with a color tint applied.
  338. public func tinted(with color: KFCrossPlatformColor) -> KFCrossPlatformImage {
  339. #if os(watchOS)
  340. return base
  341. #else
  342. return apply(.tint(color))
  343. #endif
  344. }
  345. // MARK: Color Control
  346. /// Create an image from `self` with color control.
  347. ///
  348. /// - Parameters:
  349. /// - brightness: Brightness changing to image.
  350. /// - contrast: Contrast changing to image.
  351. /// - saturation: Saturation changing to image.
  352. /// - inputEV: InputEV changing to image.
  353. /// - Returns: An image with color control applied.
  354. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> KFCrossPlatformImage {
  355. #if os(watchOS)
  356. return base
  357. #else
  358. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  359. #endif
  360. }
  361. /// Return an image with given scale.
  362. ///
  363. /// - Parameter scale: Target scale factor the new image should have.
  364. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  365. public func scaled(to scale: CGFloat) -> KFCrossPlatformImage {
  366. guard scale != self.scale else {
  367. return base
  368. }
  369. guard let cgImage = cgImage else {
  370. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  371. return base
  372. }
  373. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  374. }
  375. }
  376. // MARK: - Decoding Image
  377. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  378. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  379. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  380. /// displayed for the first time.
  381. ///
  382. /// - Note: This method only works for CG-based image. The current image scale is kept.
  383. /// For any non-CG-based image or animated image, `base` itself is returned.
  384. public var decoded: KFCrossPlatformImage { return decoded(scale: scale) }
  385. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  386. /// return the data from it. This could improve the drawing performance when an image is just created from
  387. /// data but not yet displayed for the first time.
  388. ///
  389. /// - Parameter scale: The given scale of target image should be.
  390. /// - Returns: The decoded image ready to be displayed.
  391. ///
  392. /// - Note: This method only works for CG-based image. The current image scale is kept.
  393. /// For any non-CG-based image or animated image, `base` itself is returned.
  394. public func decoded(scale: CGFloat) -> KFCrossPlatformImage {
  395. // Prevent animated image (GIF) losing it's images
  396. #if os(iOS)
  397. if imageSource != nil { return base }
  398. #else
  399. if images != nil { return base }
  400. #endif
  401. guard let imageRef = cgImage else {
  402. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  403. return base
  404. }
  405. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  406. return draw(to: size, inverting: true, scale: scale) { context in
  407. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  408. return true
  409. }
  410. }
  411. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  412. /// return the data from it. This could improve the drawing performance when an image is just created from
  413. /// data but not yet displayed for the first time.
  414. ///
  415. /// - Parameter context: The context for drawing.
  416. /// - Returns: The decoded image ready to be displayed.
  417. ///
  418. /// - Note: This method only works for CG-based image. The current image scale is kept.
  419. /// For any non-CG-based image or animated image, `base` itself is returned.
  420. public func decoded(on context: CGContext) -> KFCrossPlatformImage {
  421. // Prevent animated image (GIF) losing it's images
  422. #if os(iOS)
  423. if imageSource != nil { return base }
  424. #else
  425. if images != nil { return base }
  426. #endif
  427. guard let refImage = cgImage else {
  428. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  429. return base
  430. }
  431. let size = CGSize(width: CGFloat(refImage.width) / scale, height: CGFloat(refImage.height) / scale)
  432. context.draw(refImage, in: CGRect(origin: .zero, size: size))
  433. guard let cgImage = context.makeImage() else {
  434. return base
  435. }
  436. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  437. }
  438. }
  439. extension KingfisherWrapper where Base: KFCrossPlatformImage {
  440. func draw(
  441. to size: CGSize,
  442. inverting: Bool = false,
  443. scale: CGFloat? = nil,
  444. refImage: KFCrossPlatformImage? = nil,
  445. draw: (CGContext) -> Bool // Whether use the refImage (`true`) or ignore image orientation (`false`)
  446. ) -> KFCrossPlatformImage
  447. {
  448. let targetScale = scale ?? self.scale
  449. GraphicsContext.begin(size: size, scale: targetScale)
  450. guard let context = GraphicsContext.current(size: size, scale: targetScale, inverting: inverting, cgImage: cgImage) else {
  451. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  452. return base
  453. }
  454. defer { GraphicsContext.end() }
  455. let useRefImage = draw(context)
  456. guard let cgImage = context.makeImage() else {
  457. return base
  458. }
  459. let ref = useRefImage ? (refImage ?? base) : nil
  460. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: ref)
  461. }
  462. #if os(macOS)
  463. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> KFCrossPlatformImage {
  464. let image = KFCrossPlatformImage(cgImage: cgImage, size: base.size)
  465. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  466. return draw(to: self.size) { context in
  467. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  468. return false
  469. }
  470. }
  471. #endif
  472. }