ImageDrawing.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522
  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 in point.
  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 in point.
  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. let newSize = size.kf.resize(to: size, for: contentMode)
  189. return resize(to: newSize)
  190. }
  191. /// Crops `base` image to a new size with a given anchor.
  192. ///
  193. /// - Parameters:
  194. /// - size: The target size.
  195. /// - anchor: The anchor point from which the size should be calculated.
  196. /// - Returns: An image with new size.
  197. ///
  198. /// - Note: This method only works for CG-based image. The current image scale is kept.
  199. /// For any non-CG-based image, `base` itself is returned.
  200. public func crop(to size: CGSize, anchorOn anchor: CGPoint) -> Image {
  201. guard let cgImage = cgImage else {
  202. assertionFailure("[Kingfisher] Crop only works for CG-based image.")
  203. return base
  204. }
  205. let rect = self.size.kf.constrainedRect(for: size, anchor: anchor)
  206. guard let image = cgImage.cropping(to: rect.scaled(scale)) else {
  207. assertionFailure("[Kingfisher] Cropping image failed.")
  208. return base
  209. }
  210. return KingfisherClass.image(cgImage: image, scale: scale, refImage: base)
  211. }
  212. // MARK: - Blur
  213. /// Creates an image with blur effect based on `base` image.
  214. ///
  215. /// - Parameter radius: The blur radius should be used when creating blur effect.
  216. /// - Returns: An image with blur effect applied.
  217. ///
  218. /// - Note: This method only works for CG-based image. The current image scale is kept.
  219. /// For any non-CG-based image, `base` itself is returned.
  220. public func blurred(withRadius radius: CGFloat) -> Image {
  221. guard let cgImage = cgImage else {
  222. assertionFailure("[Kingfisher] Blur only works for CG-based image.")
  223. return base
  224. }
  225. // http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
  226. // let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
  227. // if d is odd, use three box-blurs of size 'd', centered on the output pixel.
  228. let s = Float(max(radius, 2.0))
  229. // We will do blur on a resized image (*0.5), so the blur radius could be half as well.
  230. // Fix the slow compiling time for Swift 3.
  231. // See https://github.com/onevcat/Kingfisher/issues/611
  232. let pi2 = 2 * Float.pi
  233. let sqrtPi2 = sqrt(pi2)
  234. var targetRadius = floor(s * 3.0 * sqrtPi2 / 4.0 + 0.5)
  235. if targetRadius.isEven { targetRadius += 1 }
  236. // Determine necessary iteration count by blur radius.
  237. let iterations: Int
  238. if radius < 0.5 {
  239. iterations = 1
  240. } else if radius < 1.5 {
  241. iterations = 2
  242. } else {
  243. iterations = 3
  244. }
  245. let w = Int(size.width)
  246. let h = Int(size.height)
  247. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  248. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  249. let data = context.data
  250. let width = vImagePixelCount(context.width)
  251. let height = vImagePixelCount(context.height)
  252. let rowBytes = context.bytesPerRow
  253. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  254. }
  255. guard let context = beginContext(size: size, scale: scale, inverting: true) else {
  256. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  257. return base
  258. }
  259. context.draw(cgImage, in: CGRect(x: 0, y: 0, width: w, height: h))
  260. endContext()
  261. var inBuffer = createEffectBuffer(context)
  262. guard let outContext = beginContext(size: size, scale: scale, inverting: true) else {
  263. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  264. return base
  265. }
  266. defer { endContext() }
  267. var outBuffer = createEffectBuffer(outContext)
  268. for _ in 0 ..< iterations {
  269. let flag = vImage_Flags(kvImageEdgeExtend)
  270. vImageBoxConvolve_ARGB8888(
  271. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  272. // Next inBuffer should be the outButter of current iteration
  273. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  274. }
  275. #if os(macOS)
  276. let result = outContext.makeImage().flatMap {
  277. fixedForRetinaPixel(cgImage: $0, to: size)
  278. }
  279. #else
  280. let result = outContext.makeImage().flatMap {
  281. Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  282. }
  283. #endif
  284. guard let blurredImage = result else {
  285. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  286. return base
  287. }
  288. return blurredImage
  289. }
  290. // MARK: - Overlay
  291. /// Creates an image from `base` image with a color overlay layer.
  292. ///
  293. /// - Parameters:
  294. /// - color: The color should be use to overlay.
  295. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
  296. /// 1.0 means transparent overlay.
  297. /// - Returns: An image with a color overlay applied.
  298. ///
  299. /// - Note: This method only works for CG-based image. The current image scale is kept.
  300. /// For any non-CG-based image, `base` itself is returned.
  301. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  302. guard let _ = cgImage else {
  303. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  304. return base
  305. }
  306. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  307. return draw(to: rect.size) { context in
  308. #if os(macOS)
  309. base.draw(in: rect)
  310. if fraction > 0 {
  311. color.withAlphaComponent(1 - fraction).set()
  312. rect.fill(using: .sourceAtop)
  313. }
  314. #else
  315. color.set()
  316. UIRectFill(rect)
  317. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  318. if fraction > 0 {
  319. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  320. }
  321. #endif
  322. }
  323. }
  324. // MARK: - Tint
  325. /// Creates an image from `base` image with a color tint.
  326. ///
  327. /// - Parameter color: The color should be used to tint `base`
  328. /// - Returns: An image with a color tint applied.
  329. public func tinted(with color: Color) -> Image {
  330. #if os(watchOS)
  331. return base
  332. #else
  333. return apply(.tint(color))
  334. #endif
  335. }
  336. // MARK: - Color Control
  337. /// Create an image from `self` with color control.
  338. ///
  339. /// - Parameters:
  340. /// - brightness: Brightness changing to image.
  341. /// - contrast: Contrast changing to image.
  342. /// - saturation: Saturation changing to image.
  343. /// - inputEV: InputEV changing to image.
  344. /// - Returns: An image with color control applied.
  345. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  346. #if os(watchOS)
  347. return base
  348. #else
  349. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  350. #endif
  351. }
  352. /// Return an image with given scale.
  353. ///
  354. /// - Parameter scale: Target scale factor the new image should have.
  355. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  356. public func scaled(to scale: CGFloat) -> Image {
  357. guard scale != self.scale else {
  358. return base
  359. }
  360. guard let cgImage = cgImage else {
  361. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  362. return base
  363. }
  364. return KingfisherClass.image(cgImage: cgImage, scale: scale, refImage: base)
  365. }
  366. }
  367. // MARK: - Decode
  368. extension KingfisherClass where Base: Image {
  369. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  370. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  371. /// displayed for the first time.
  372. ///
  373. /// - Note: This method only works for CG-based image. The current image scale is kept.
  374. /// For any non-CG-based image or animated image, `base` itself is returned.
  375. public var decoded: Image { return decoded(scale: scale) }
  376. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  377. /// return the data from it. This could improve the drawing performance when an image is just created from
  378. /// data but not yet displayed for the first time.
  379. ///
  380. /// - Parameter scale: The given scale of target image should be.
  381. /// - Returns: The decoded image ready to be displayed.
  382. ///
  383. /// - Note: This method only works for CG-based image. The current image scale is kept.
  384. /// For any non-CG-based image or animated image, `base` itself is returned.
  385. public func decoded(scale: CGFloat) -> Image {
  386. // Prevent animated image (GIF) losing it's images
  387. #if os(iOS)
  388. if imageSource != nil { return base }
  389. #else
  390. if images != nil { return base }
  391. #endif
  392. guard let imageRef = cgImage else {
  393. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  394. return base
  395. }
  396. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  397. return draw(to: size, inverting: true, scale: scale) { context in
  398. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  399. }
  400. }
  401. }
  402. extension KingfisherClass where Base: Image {
  403. func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? {
  404. #if os(macOS)
  405. guard let rep = NSBitmapImageRep(
  406. bitmapDataPlanes: nil,
  407. pixelsWide: Int(size.width),
  408. pixelsHigh: Int(size.height),
  409. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  410. samplesPerPixel: 4,
  411. hasAlpha: true,
  412. isPlanar: false,
  413. colorSpaceName: .calibratedRGB,
  414. bytesPerRow: 0,
  415. bitsPerPixel: 0) else
  416. {
  417. assertionFailure("[Kingfisher] Image representation cannot be created.")
  418. return nil
  419. }
  420. rep.size = size
  421. NSGraphicsContext.saveGraphicsState()
  422. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  423. assertionFailure("[Kingfisher] Image contenxt cannot be created.")
  424. return nil
  425. }
  426. NSGraphicsContext.current = context
  427. return context.cgContext
  428. #else
  429. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  430. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  431. if inverting { // If drawing a CGImage, we need to make context flipped.
  432. context.scaleBy(x: 1.0, y: -1.0)
  433. context.translateBy(x: 0, y: -size.height)
  434. }
  435. return context
  436. #endif
  437. }
  438. func endContext() {
  439. #if os(macOS)
  440. NSGraphicsContext.restoreGraphicsState()
  441. #else
  442. UIGraphicsEndImageContext()
  443. #endif
  444. }
  445. func draw(to size: CGSize, inverting: Bool = false, scale: CGFloat? = nil, draw: (CGContext) -> Void) -> Image {
  446. let targetScale = scale ?? self.scale
  447. guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else {
  448. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  449. return base
  450. }
  451. defer { endContext() }
  452. draw(context)
  453. guard let cgImage = context.makeImage() else {
  454. return base
  455. }
  456. return KingfisherClass.image(cgImage: cgImage, scale: targetScale, refImage: base)
  457. }
  458. #if os(macOS)
  459. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  460. let image = Image(cgImage: cgImage, size: base.size)
  461. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  462. return draw(to: self.size) { context in
  463. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  464. }
  465. }
  466. #endif
  467. }