You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

529 lines
20 KiB

  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)
  28. import AppKit
  29. #endif
  30. #if canImport(UIKit)
  31. import UIKit
  32. #endif
  33. // MARK: - Image Transforming
  34. extension KingfisherWrapper 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
  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. #if swift(>=4.2)
  124. path.windingRule = .evenOdd
  125. #else
  126. path.windingRule = .evenOddWindingRule
  127. #endif
  128. path.addClip()
  129. base.draw(in: rect)
  130. #else
  131. guard let context = UIGraphicsGetCurrentContext() else {
  132. assertionFailure("[Kingfisher] Failed to create CG context for image.")
  133. return
  134. }
  135. if let backgroundColor = backgroundColor {
  136. let rectPath = UIBezierPath(rect: rect)
  137. backgroundColor.setFill()
  138. rectPath.fill()
  139. }
  140. let path = UIBezierPath(
  141. roundedRect: rect,
  142. byRoundingCorners: corners.uiRectCorner,
  143. cornerRadii: CGSize(width: radius, height: radius)
  144. )
  145. context.addPath(path.cgPath)
  146. context.clip()
  147. base.draw(in: rect)
  148. #endif
  149. }
  150. }
  151. #if os(iOS) || os(tvOS)
  152. func resize(to size: CGSize, for contentMode: UIView.ContentMode) -> Image {
  153. switch contentMode {
  154. case .scaleAspectFit:
  155. return resize(to: size, for: .aspectFit)
  156. case .scaleAspectFill:
  157. return resize(to: size, for: .aspectFill)
  158. default:
  159. return resize(to: size)
  160. }
  161. }
  162. #endif
  163. // MARK: Resizing
  164. /// Resizes `base` image to an image with new size.
  165. ///
  166. /// - Parameter size: The target size in point.
  167. /// - Returns: An image with new size.
  168. /// - Note: This method only works for CG-based image. The current image scale is kept.
  169. /// For any non-CG-based image, `base` itself is returned.
  170. public func resize(to size: CGSize) -> Image {
  171. guard let _ = cgImage else {
  172. assertionFailure("[Kingfisher] Resize only works for CG-based image.")
  173. return base
  174. }
  175. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  176. return draw(to: size) { _ in
  177. #if os(macOS)
  178. base.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  179. #else
  180. base.draw(in: rect)
  181. #endif
  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) -> Image {
  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) -> Image {
  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) -> Image {
  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 = Float(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 * Float.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. let rowBytes = Int(CGFloat(cgImage.bytesPerRow))
  255. func createEffectBuffer(_ context: CGContext) -> vImage_Buffer {
  256. let data = context.data
  257. let width = vImagePixelCount(context.width)
  258. let height = vImagePixelCount(context.height)
  259. let rowBytes = context.bytesPerRow
  260. return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
  261. }
  262. guard let context = beginContext(size: size, scale: scale, inverting: true) 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. endContext()
  268. var inBuffer = createEffectBuffer(context)
  269. guard let outContext = beginContext(size: size, scale: scale, inverting: true) else {
  270. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  271. return base
  272. }
  273. defer { endContext() }
  274. var outBuffer = createEffectBuffer(outContext)
  275. for _ in 0 ..< iterations {
  276. let flag = vImage_Flags(kvImageEdgeExtend)
  277. vImageBoxConvolve_ARGB8888(
  278. &inBuffer, &outBuffer, nil, 0, 0, UInt32(targetRadius), UInt32(targetRadius), nil, flag)
  279. // Next inBuffer should be the outButter of current iteration
  280. (inBuffer, outBuffer) = (outBuffer, inBuffer)
  281. }
  282. #if os(macOS)
  283. let result = outContext.makeImage().flatMap {
  284. fixedForRetinaPixel(cgImage: $0, to: size)
  285. }
  286. #else
  287. let result = outContext.makeImage().flatMap {
  288. Image(cgImage: $0, scale: base.scale, orientation: base.imageOrientation)
  289. }
  290. #endif
  291. guard let blurredImage = result else {
  292. assertionFailure("[Kingfisher] Can not make an blurred image within this context.")
  293. return base
  294. }
  295. return blurredImage
  296. }
  297. // MARK: Overlay
  298. /// Creates an image from `base` image with a color overlay layer.
  299. ///
  300. /// - Parameters:
  301. /// - color: The color should be use to overlay.
  302. /// - fraction: Fraction of input color. From 0.0 to 1.0. 0.0 means solid color,
  303. /// 1.0 means transparent overlay.
  304. /// - Returns: An image with a color overlay applied.
  305. ///
  306. /// - Note: This method only works for CG-based image. The current image scale is kept.
  307. /// For any non-CG-based image, `base` itself is returned.
  308. public func overlaying(with color: Color, fraction: CGFloat) -> Image {
  309. guard let _ = cgImage else {
  310. assertionFailure("[Kingfisher] Overlaying only works for CG-based image.")
  311. return base
  312. }
  313. let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
  314. return draw(to: rect.size) { context in
  315. #if os(macOS)
  316. base.draw(in: rect)
  317. if fraction > 0 {
  318. color.withAlphaComponent(1 - fraction).set()
  319. rect.fill(using: .sourceAtop)
  320. }
  321. #else
  322. color.set()
  323. UIRectFill(rect)
  324. base.draw(in: rect, blendMode: .destinationIn, alpha: 1.0)
  325. if fraction > 0 {
  326. base.draw(in: rect, blendMode: .sourceAtop, alpha: fraction)
  327. }
  328. #endif
  329. }
  330. }
  331. // MARK: Tint
  332. /// Creates an image from `base` image with a color tint.
  333. ///
  334. /// - Parameter color: The color should be used to tint `base`
  335. /// - Returns: An image with a color tint applied.
  336. public func tinted(with color: Color) -> Image {
  337. #if os(watchOS)
  338. return base
  339. #else
  340. return apply(.tint(color))
  341. #endif
  342. }
  343. // MARK: Color Control
  344. /// Create an image from `self` with color control.
  345. ///
  346. /// - Parameters:
  347. /// - brightness: Brightness changing to image.
  348. /// - contrast: Contrast changing to image.
  349. /// - saturation: Saturation changing to image.
  350. /// - inputEV: InputEV changing to image.
  351. /// - Returns: An image with color control applied.
  352. public func adjusted(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) -> Image {
  353. #if os(watchOS)
  354. return base
  355. #else
  356. return apply(.colorControl((brightness, contrast, saturation, inputEV)))
  357. #endif
  358. }
  359. /// Return an image with given scale.
  360. ///
  361. /// - Parameter scale: Target scale factor the new image should have.
  362. /// - Returns: The image with target scale. If the base image is already in the scale, `base` will be returned.
  363. public func scaled(to scale: CGFloat) -> Image {
  364. guard scale != self.scale else {
  365. return base
  366. }
  367. guard let cgImage = cgImage else {
  368. assertionFailure("[Kingfisher] Scaling only works for CG-based image.")
  369. return base
  370. }
  371. return KingfisherWrapper.image(cgImage: cgImage, scale: scale, refImage: base)
  372. }
  373. }
  374. // MARK: - Decoding Image
  375. extension KingfisherWrapper where Base: Image {
  376. /// Returns the decoded image of the `base` image. It will draw the image in a plain context and return the data
  377. /// from it. This could improve the drawing performance when an image is just created from data but not yet
  378. /// displayed for the first time.
  379. ///
  380. /// - Note: This method only works for CG-based image. The current image scale is kept.
  381. /// For any non-CG-based image or animated image, `base` itself is returned.
  382. public var decoded: Image { return decoded(scale: scale) }
  383. /// Returns decoded image of the `base` image at a given scale. It will draw the image in a plain context and
  384. /// return the data from it. This could improve the drawing performance when an image is just created from
  385. /// data but not yet displayed for the first time.
  386. ///
  387. /// - Parameter scale: The given scale of target image should be.
  388. /// - Returns: The decoded image ready to be displayed.
  389. ///
  390. /// - Note: This method only works for CG-based image. The current image scale is kept.
  391. /// For any non-CG-based image or animated image, `base` itself is returned.
  392. public func decoded(scale: CGFloat) -> Image {
  393. // Prevent animated image (GIF) losing it's images
  394. #if os(iOS)
  395. if imageSource != nil { return base }
  396. #else
  397. if images != nil { return base }
  398. #endif
  399. guard let imageRef = cgImage else {
  400. assertionFailure("[Kingfisher] Decoding only works for CG-based image.")
  401. return base
  402. }
  403. let size = CGSize(width: CGFloat(imageRef.width) / scale, height: CGFloat(imageRef.height) / scale)
  404. return draw(to: size, inverting: true, scale: scale) { context in
  405. context.draw(imageRef, in: CGRect(origin: .zero, size: size))
  406. }
  407. }
  408. }
  409. extension KingfisherWrapper where Base: Image {
  410. func beginContext(size: CGSize, scale: CGFloat, inverting: Bool = false) -> CGContext? {
  411. #if os(macOS)
  412. guard let rep = NSBitmapImageRep(
  413. bitmapDataPlanes: nil,
  414. pixelsWide: Int(size.width),
  415. pixelsHigh: Int(size.height),
  416. bitsPerSample: cgImage?.bitsPerComponent ?? 8,
  417. samplesPerPixel: 4,
  418. hasAlpha: true,
  419. isPlanar: false,
  420. colorSpaceName: .calibratedRGB,
  421. bytesPerRow: 0,
  422. bitsPerPixel: 0) else
  423. {
  424. assertionFailure("[Kingfisher] Image representation cannot be created.")
  425. return nil
  426. }
  427. rep.size = size
  428. NSGraphicsContext.saveGraphicsState()
  429. guard let context = NSGraphicsContext(bitmapImageRep: rep) else {
  430. assertionFailure("[Kingfisher] Image context cannot be created.")
  431. return nil
  432. }
  433. NSGraphicsContext.current = context
  434. return context.cgContext
  435. #else
  436. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  437. guard let context = UIGraphicsGetCurrentContext() else { return nil }
  438. if inverting { // If drawing a CGImage, we need to make context flipped.
  439. context.scaleBy(x: 1.0, y: -1.0)
  440. context.translateBy(x: 0, y: -size.height)
  441. }
  442. return context
  443. #endif
  444. }
  445. func endContext() {
  446. #if os(macOS)
  447. NSGraphicsContext.restoreGraphicsState()
  448. #else
  449. UIGraphicsEndImageContext()
  450. #endif
  451. }
  452. func draw(to size: CGSize, inverting: Bool = false, scale: CGFloat? = nil, refImage: Image? = nil, draw: (CGContext) -> Void) -> Image {
  453. let targetScale = scale ?? self.scale
  454. guard let context = beginContext(size: size, scale: targetScale, inverting: inverting) else {
  455. assertionFailure("[Kingfisher] Failed to create CG context for blurring image.")
  456. return base
  457. }
  458. defer { endContext() }
  459. draw(context)
  460. guard let cgImage = context.makeImage() else {
  461. return base
  462. }
  463. return KingfisherWrapper.image(cgImage: cgImage, scale: targetScale, refImage: refImage ?? base)
  464. }
  465. #if os(macOS)
  466. func fixedForRetinaPixel(cgImage: CGImage, to size: CGSize) -> Image {
  467. let image = Image(cgImage: cgImage, size: base.size)
  468. let rect = CGRect(origin: CGPoint(x: 0, y: 0), size: size)
  469. return draw(to: self.size) { context in
  470. image.draw(in: rect, from: .zero, operation: .copy, fraction: 1.0)
  471. }
  472. }
  473. #endif
  474. }