ImageDrawing.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. //
  2. // ImageDrawing.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2018/09/28.
  6. //
  7. // Copyright (c) 2018 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)
  28. import AppKit
  29. #endif
  30. #if canImport(UIKit)
  31. import UIKit
  32. #endif
  33. // MARK: - Image Transforming
  34. extension KingfisherClass where Base: Image {
  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: Color? = nil) -> Image
  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. }
  62. }
  63. #endif
  64. #if os(macOS)
  65. // MARK: - Compositing Operation
  66. /// Creates image from `base` image and apply compositing operation.
  67. ///
  68. /// - Parameters:
  69. /// - compositingOperation: The compositing operation of creating image.
  70. /// - alpha: The alpha should be used for image.
  71. /// - backgroundColor: The background color for the output image.
  72. /// - Returns: An image with compositing operation applied.
  73. ///
  74. /// - Note: This method only works for CG-based image. For any non-CG-based image, `base` itself is returned.
  75. public func image(withCompositingOperation compositingOperation: NSCompositingOperation,
  76. alpha: CGFloat = 1.0,
  77. backgroundColor: Color? = nil) -> Image
  78. {
  79. guard let _ = cgImage else {
  80. assertionFailure("[Kingfisher] Compositing Operation image only works for CG-based image.")
  81. return base
  82. }
  83. let rect = CGRect(origin: .zero, size: size)
  84. return draw(to: rect.size) { _ in
  85. if let backgroundColor = backgroundColor {
  86. backgroundColor.setFill()
  87. rect.fill()
  88. }
  89. base.draw(in: rect, from: .zero, operation: compositingOperation, fraction: alpha)
  90. }
  91. }
  92. #endif
  93. // MARK: - Round Corner
  94. /// Creates a round corner image from on `base` image.
  95. ///
  96. /// - Parameters:
  97. /// - radius: The round corner radius of creating image.
  98. /// - size: The target size of creating image.
  99. /// - corners: The target corners which will be applied rounding.
  100. /// - backgroundColor: The background color for the output image
  101. /// - Returns: An image with round corner of `self`.
  102. ///
  103. /// - Note: This method only works for CG-based image. The current image scale is kept.
  104. /// For any non-CG-based image, `base` itself is returned.
  105. public func image(withRoundRadius radius: CGFloat,
  106. fit size: CGSize,
  107. roundingCorners corners: RectCorner = .all,
  108. backgroundColor: Color? = nil) -> Image
  109. {
  110. guard let _ = cgImage else {
  111. assertionFailure("[Kingfisher] Round corner image only works for CG-based image.")
  112. return base
  113. }
  114. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  115. return draw(to: size) { _ in
  116. #if os(macOS)
  117. if let backgroundColor = backgroundColor {
  118. let rectPath = NSBezierPath(rect: rect)
  119. backgroundColor.setFill()
  120. rectPath.fill()
  121. }
  122. let path = NSBezierPath(roundedRect: rect, byRoundingCorners: corners, radius: radius)
  123. path.windingRule = .evenOdd
  124. path.addClip()
  125. base.draw(in: rect)
  126. #else
  127. guard let context = UIGraphicsGetCurrentContext() else {
  128. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  129. return
  130. }
  131. if let backgroundColor = backgroundColor {
  132. let rectPath = UIBezierPath(rect: rect)
  133. backgroundColor.setFill()
  134. rectPath.fill()
  135. }
  136. let path = UIBezierPath(roundedRect: rect,
  137. byRoundingCorners: corners.uiRectCorner,
  138. cornerRadii: CGSize(width: radius, height: radius)).cgPath
  139. context.addPath(path)
  140. context.clip()
  141. base.draw(in: rect)
  142. #endif
  143. }
  144. }
  145. #if os(iOS) || os(tvOS)
  146. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> Image {
  147. switch contentMode {
  148. case .scaleAspectFit:
  149. return resize(to: size, for: .aspectFit)
  150. case .scaleAspectFill:
  151. return resize(to: size, for: .aspectFill)
  152. default:
  153. return resize(to: size)
  154. }
  155. }
  156. #endif
  157. // MARK: - Resize
  158. /// Resizes `base` image to an image with new size.
  159. ///
  160. /// - Parameter size: The target size.
  161. /// - Returns: An image with new size.
  162. /// - Note: This method only works for CG-based image. The current image scale is kept.
  163. /// For any non-CG-based image, `base` itself is returned.
  164. public func resize(to size: CGSize) -> Image {
  165. guard let _ = cgImage else {
  166. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  167. return base
  168. }
  169. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  170. return draw(to: size) { _ in
  171. #if os(macOS)
  172. base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  173. #else
  174. base.draw(in: rect)
  175. #endif
  176. }
  177. }
  178. /// Resizes `base` image to an image of new size, respecting the given content mode.
  179. ///
  180. /// - Parameters:
  181. /// - size: The target size.
  182. /// - contentMode: Content mode of output image should be.
  183. /// - Returns: An image with new size.
  184. ///
  185. /// - Note: This method only works for CG-based image. The current image scale is kept.
  186. /// For any non-CG-based image, `base` itself is returned.
  187. public func resize(to size: CGSize, for contentMode: ContentMode) -> Image {
  188. switch contentMode {
  189. case .aspectFit:
  190. let newSize = self.size.kf.constrained(size)
  191. return resize(to: newSize)
  192. case .aspectFill:
  193. let newSize = self.size.kf.filling(size)
  194. return resize(to: newSize)
  195. case .none:
  196. return resize(to: size)
  197. }
  198. }
  199. /// Crops `base` image to a new size with a given anchor.
  200. ///
  201. /// - Parameters:
  202. /// - size: The target size.
  203. /// - anchor: The anchor point from which the size should be calculated.
  204. /// - Returns: An image with new size.
  205. ///
  206. /// - Note: This method only works for CG-based image. The current image scale is kept.
  207. /// For any non-CG-based image, `base` itself is returned.
  208. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  209. guard let cgImage = cgImage else {
  210. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  211. return base
  212. }
  213. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  214. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  215. assertionFailure("[Kingfisher] Cropping image failed.")
  216. return base
  217. }
  218. return KingfisherClass.image(cgImage: image, scale: scale, refImage: base)
  219. }
  220. // MARK: - Blur
  221. /// Creates an image with blur effect based on `base` image.
  222. ///
  223. /// - Parameter radius: The blur radius should be used when creating blur effect.
  224. /// - Returns: An image with blur effect applied.
  225. ///
  226. /// - Note: This method only works for CG-based image. The current image scale is kept.
  227. /// For any non-CG-based image, `base` itself is returned.
  228. public func blurred(withRadius radius: CGFloat) -> Image {
  229. guard let cgImage = cgImage else {
  230. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  231. return base
  232. }
  233. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  234. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  235. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  236. let s = Float(max(radius, 2.0))
  237. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  238. // Fix the slow compiling time for Swift 3.
  239. // See https://github.com/onevcat/Kingfisher/issues/611
  240. let pi2 = 2 * Float.pi
  241. let sqrtPi2 = sqrt(pi2)
  242. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  243. if targetRadius.isEven { targetRadius += 1 }
  244. // Determine necessary iteration count by blur radius.
  245. let iterations: Int
  246. if radius < 0.5 {
  247. iterations = 1
  248. } else if radius < 1.5 {
  249. iterations = 2
  250. } else {
  251. iterations = 3
  252. }
  253. let w = Int(size.width)
  254. let h = Int(size.height)
  255. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  256. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  257. let data = context.data
  258. let width = vImagePixelCount(context.width)
  259. let height = vImagePixelCount(context.height)
  260. let rowBytes = context.bytesPerRow
  261. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  262. }
  263. guard let context = beginContext(size: size, scale: scale, inverting: true) else {
  264. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  265. return base
  266. }
  267. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  268. endContext()
  269. var inBuffer = createEffectBuffer(context)
  270. guard let outContext = beginContext(size: size, scale: scale, inverting: true) else {
  271. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  272. return base
  273. }
  274. defer { endContext() }
  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. Image(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: Color, fraction: CGFloat) -> Image {
  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. }
  331. }
  332. // MARK: - Tint
  333. /// Creates an image from `base` image with a color tint.
  334. ///
  335. /// - Parameter color: The color should be used to tint `base`
  336. /// - Returns: An image with a color tint applied.
  337. public func tinted(with color: Color) -> Image {
  338. #if os(watchOS)
  339. return base
  340. #else
  341. return apply(.tint(color))
  342. #endif
  343. }
  344. // MARK: - Color Control
  345. /// Create an image from `self` with color control.
  346. ///
  347. /// - Parameters:
  348. /// - brightness: Brightness changing to image.
  349. /// - contrast: Contrast changing to image.
  350. /// - saturation: Saturation changing to image.
  351. /// - inputEV: InputEV changing to image.
  352. /// - Returns: An image with color control applied.
  353. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  354. #if os(watchOS)
  355. return base
  356. #else
  357. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  358. #endif
  359. }
  360. /// Return an image with given scale.
  361. ///
  362. /// - Parameter scale: Target scale factor the new image should have.
  363. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  364. public func scaled(to scale: CGFloat) -> Image {
  365. guard scale != self.scale else {
  366. return base
  367. }
  368. guard let cgImage = cgImage else {
  369. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  370. return base
  371. }
  372. return KingfisherClass.image(cgImage: cgImage, scale: scale, refImage: base)
  373. }
  374. }
  375. // MARK: - Decode
  376. extension KingfisherClass where Base: Image {
  377. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  378. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  379. /// displayed for the first time.
  380. ///
  381. /// - Note: This method only works for CG-based image. The current image scale is kept.
  382. /// For any non-CG-based image or animated image, `base` itself is returned.
  383. public var decoded: Image { return decoded(scale: scale) }
  384. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  385. /// return the data from it. This could improve the drawing performance when an image is just created from
  386. /// data but not yet displayed for the first time.
  387. ///
  388. /// - Parameter scale: The given scale of target image should be.
  389. /// - Returns: The decoded image ready to be displayed.
  390. ///
  391. /// - Note: This method only works for CG-based image. The current image scale is kept.
  392. /// For any non-CG-based image or animated image, `base` itself is returned.
  393. public func decoded(scale: CGFloat) -> Image {
  394. // Prevent animated image (GIF) losing it's images
  395. #if os(iOS)
  396. if imageSource != nil { return base }
  397. #else
  398. if images != nil { return base }
  399. #endif
  400. guard let imageRef = cgImage else {
  401. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  402. return base
  403. }
  404. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  405. return draw(to: size, inverting: true, scale: scale) { context in
  406. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  407. }
  408. }
  409. }
  410. extension KingfisherClass where Base: Image {
  411. func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? {
  412. #if os(macOS)
  413. guard let rep = NSBitmapImageRep(
  414. bitmapDataPlanes: nil,
  415. pixelsWide: Int(size.width),
  416. pixelsHigh: Int(size.height),
  417. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  418. samplesPerPixel: 4,
  419. hasAlpha: true,
  420. isPlanar: false,
  421. colorSpaceName: .calibratedRGB,
  422. bytesPerRow: 0,
  423. bitsPerPixel: 0) else
  424. {
  425. assertionFailure("[Kingfisher] Image representation cannot be created.")
  426. return nil
  427. }
  428. rep.size = size
  429. NSGraphicsContext.saveGraphicsState()
  430. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  431. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  432. return nil
  433. }
  434. NSGraphicsContext.current = context
  435. return context.cgContext
  436. #else
  437. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  438. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  439. if inverting { // If drawing a CGImage, we need to make context flipped.
  440. context.scaleBy(x: 1.0, y: -1.0)
  441. context.translateBy(x: 0, y: -size.height)
  442. }
  443. return context
  444. #endif
  445. }
  446. func endContext() {
  447. #if os(macOS)
  448. NSGraphicsContext.restoreGraphicsState()
  449. #else
  450. UIGraphicsEndImageContext()
  451. #endif
  452. }
  453. func draw(to size: CGSize, inverting: Bool = false, scale: CGFloat? = nil, draw: (CGContext) -> Void) -> Image {
  454. let targetScale = scale ?? self.scale
  455. guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else {
  456. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  457. return base
  458. }
  459. defer { endContext() }
  460. draw(context)
  461. guard let cgImage = context.makeImage() else {
  462. return base
  463. }
  464. return KingfisherClass.image(cgImage: cgImage, scale: targetScale, refImage: base)
  465. }
  466. #if os(macOS)
  467. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  468. let image = Image(cgImage: cgImage, size: base.size)
  469. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  470. return draw(to: self.size) { context in
  471. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  472. }
  473. }
  474. #endif
  475. }