GraphicsContext.swift 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. //
  2. // GraphicsContext.swift
  3. // Kingfisher
  4. //
  5. // Created by taras on 19/04/2021.
  6. //
  7. // Copyright (c) 2021 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. #if os(macOS) || os(watchOS)
  27. #if canImport(AppKit) && !targetEnvironment(macCatalyst)
  28. import AppKit
  29. #endif
  30. #if canImport(UIKit)
  31. import UIKit
  32. #endif
  33. enum GraphicsContext {
  34. static func begin(size: CGSize, scale: CGFloat) {
  35. #if os(macOS)
  36. NSGraphicsContext.saveGraphicsState()
  37. #elseif os(watchOS)
  38. UIGraphicsBeginImageContextWithOptions(size, false, scale)
  39. #else
  40. assertionFailure("This method is deprecated on the current platform and should not be used.")
  41. #endif
  42. }
  43. static func current(size: CGSize, scale: CGFloat, inverting: Bool, cgImage: CGImage?) -> CGContext? {
  44. #if os(macOS)
  45. let descriptor = BitmapContextDescriptor(size: size, cgImage: cgImage)
  46. guard let context = descriptor.makeContext() else {
  47. assertionFailure("[Kingfisher] Image context cannot be created.")
  48. return nil
  49. }
  50. let graphicsContext = NSGraphicsContext(cgContext: context, flipped: false)
  51. graphicsContext.imageInterpolation = .high
  52. NSGraphicsContext.current = graphicsContext
  53. return graphicsContext.cgContext
  54. #elseif os(watchOS)
  55. guard let context = UIGraphicsGetCurrentContext() else {
  56. return nil
  57. }
  58. if inverting { // If drawing a CGImage, we need to make context flipped.
  59. context.scaleBy(x: 1.0, y: -1.0)
  60. context.translateBy(x: 0, y: -size.height)
  61. }
  62. return context
  63. #else
  64. assertionFailure("This method is deprecated on the current platform and should not be used.")
  65. return nil
  66. #endif
  67. }
  68. static func end() {
  69. #if os(macOS)
  70. NSGraphicsContext.restoreGraphicsState()
  71. #elseif os(watchOS)
  72. UIGraphicsEndImageContext()
  73. #else
  74. assertionFailure("This method is deprecated on the current platform and should not be used.")
  75. #endif
  76. }
  77. }
  78. #endif
  79. #if os(macOS)
  80. private struct BitmapContextDescriptor {
  81. let width: Int
  82. let height: Int
  83. let bitsPerComponent: Int
  84. let bytesPerRow: Int
  85. let colorSpace: CGColorSpace
  86. let bitmapInfo: CGBitmapInfo
  87. init(size: CGSize, cgImage: CGImage?) {
  88. width = max(Int(size.width.rounded(.down)), 1)
  89. height = max(Int(size.height.rounded(.down)), 1)
  90. colorSpace = BitmapContextDescriptor.resolveColorSpace(from: cgImage)
  91. bitsPerComponent = BitmapContextDescriptor.supportedBitsPerComponent(from: cgImage)
  92. let hasAlpha = BitmapContextDescriptor.containsAlpha(from: cgImage)
  93. bitmapInfo = BitmapContextDescriptor.bitmapInfo(hasAlpha: hasAlpha)
  94. let componentsPerPixel = colorSpace.numberOfComponents + 1 // Reserve an alpha (or skip) slot.
  95. let bitsPerPixel = componentsPerPixel * bitsPerComponent
  96. bytesPerRow = BitmapContextDescriptor.alignedBytesPerRow(bitsPerPixel: bitsPerPixel, width: width)
  97. }
  98. func makeContext() -> CGContext? {
  99. CGContext(
  100. data: nil,
  101. width: width,
  102. height: height,
  103. bitsPerComponent: bitsPerComponent,
  104. bytesPerRow: bytesPerRow,
  105. space: colorSpace,
  106. bitmapInfo: bitmapInfo.rawValue
  107. )
  108. }
  109. private static func supportedBitsPerComponent(from cgImage: CGImage?) -> Int {
  110. guard let bits = cgImage?.bitsPerComponent, bits > 0 else { return 8 }
  111. if bits <= 8 { return 8 }
  112. return 16
  113. }
  114. private static func resolveColorSpace(from cgImage: CGImage?) -> CGColorSpace {
  115. guard let cgColorSpace = cgImage?.colorSpace else {
  116. return CGColorSpaceCreateDeviceRGB()
  117. }
  118. let components = cgColorSpace.numberOfComponents
  119. if components == 1 || components == 3 {
  120. return cgColorSpace
  121. }
  122. return CGColorSpaceCreateDeviceRGB()
  123. }
  124. private static func containsAlpha(from cgImage: CGImage?) -> Bool {
  125. guard let alphaInfo = cgImage?.alphaInfo else { return true }
  126. switch alphaInfo {
  127. case .none, .noneSkipFirst, .noneSkipLast:
  128. return false
  129. default:
  130. return true
  131. }
  132. }
  133. private static func bitmapInfo(hasAlpha: Bool) -> CGBitmapInfo {
  134. let alphaInfo: CGImageAlphaInfo = hasAlpha ? .premultipliedLast : .noneSkipLast
  135. return CGBitmapInfo(rawValue: alphaInfo.rawValue)
  136. }
  137. private static func alignedBytesPerRow(bitsPerPixel: Int, width: Int) -> Int {
  138. let rawBytes = (bitsPerPixel * width + 7) / 8
  139. return (rawBytes + 0x3F) & ~0x3F
  140. }
  141. }
  142. #endif