ImageDrawing.swift 21 KB

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