MKGradientGenerator.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. /*
  2. The MIT License (MIT)
  3. Copyright (c) 2015 Max Konovalov
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. import UIKit
  21. internal final class GradientGenerator {
  22. var scale: CGFloat = UIScreen.main.scale {
  23. didSet {
  24. if scale != oldValue {
  25. reset()
  26. }
  27. }
  28. }
  29. var size: CGSize = .zero {
  30. didSet {
  31. if size != oldValue {
  32. reset()
  33. }
  34. }
  35. }
  36. var colors: [CGColor] = [] {
  37. didSet {
  38. if colors != oldValue {
  39. reset()
  40. }
  41. }
  42. }
  43. var locations: [Float] = [] {
  44. didSet {
  45. if locations != oldValue {
  46. reset()
  47. }
  48. }
  49. }
  50. var startPoint: CGPoint = CGPoint(x: 0.5, y: 0.5) {
  51. didSet {
  52. if startPoint != oldValue {
  53. reset()
  54. }
  55. }
  56. }
  57. var endPoint: CGPoint = CGPoint(x: 1.0, y: 0.5) {
  58. didSet {
  59. if endPoint != oldValue {
  60. reset()
  61. }
  62. }
  63. }
  64. private var generatedImage: CGImage?
  65. func reset() {
  66. generatedImage = nil
  67. }
  68. func image() -> CGImage {
  69. if let image = generatedImage {
  70. return image
  71. }
  72. let w = Int(size.width * scale)
  73. let h = Int(size.height * scale)
  74. let bitsPerComponent: Int = MemoryLayout<UInt8>.size * 8
  75. let bytesPerPixel: Int = bitsPerComponent * 4 / 8
  76. var data = [ARGB]()
  77. for y in 0..<h {
  78. for x in 0..<w {
  79. let c = pixelDataForGradient(at: CGPoint(x: x, y: y),
  80. size: CGSize(width: w, height: h),
  81. colors: colors,
  82. locations: locations,
  83. startPoint: startPoint,
  84. endPoint: endPoint)
  85. data.append(c)
  86. }
  87. }
  88. let colorSpace = CGColorSpaceCreateDeviceRGB()
  89. let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
  90. let ctx = CGContext(data: &data, width: w, height: h, bitsPerComponent: bitsPerComponent, bytesPerRow: w * bytesPerPixel, space: colorSpace, bitmapInfo: bitmapInfo.rawValue)!
  91. ctx.interpolationQuality = .none
  92. ctx.setShouldAntialias(false)
  93. let img = ctx.makeImage()!
  94. generatedImage = img
  95. return img
  96. }
  97. private func pixelDataForGradient(at point: CGPoint,
  98. size: CGSize,
  99. colors: [CGColor],
  100. locations: [Float],
  101. startPoint: CGPoint,
  102. endPoint: CGPoint) -> ARGB {
  103. let t = conicalGradientStop(point, size, startPoint, endPoint)
  104. return interpolatedColor(t, colors, locations)
  105. }
  106. private func conicalGradientStop(_ point: CGPoint, _ size: CGSize, _ g0: CGPoint, _ g1: CGPoint) -> Float {
  107. let c = CGPoint(x: size.width * g0.x, y: size.height * g0.y)
  108. let s = CGPoint(x: size.width * (g1.x - g0.x), y: size.height * (g1.y - g0.y))
  109. let q = atan2(s.y, s.x)
  110. let p = CGPoint(x: point.x - c.x, y: point.y - c.y)
  111. var a = atan2(p.y, p.x) - q
  112. if a < 0 {
  113. a += 2 * .pi
  114. }
  115. let t = a / (2 * .pi)
  116. return Float(t)
  117. }
  118. private func interpolatedColor(_ t: Float, _ colors: [CGColor], _ locations: [Float]) -> ARGB {
  119. assert(!colors.isEmpty)
  120. assert(colors.count == locations.count)
  121. var p0: Float = 0
  122. var p1: Float = 1
  123. var c0 = colors.first!
  124. var c1 = colors.last!
  125. for (i, v) in locations.enumerated() {
  126. if v > p0 && t >= v {
  127. p0 = v
  128. c0 = colors[i]
  129. }
  130. if v < p1 && t <= v {
  131. p1 = v
  132. c1 = colors[i]
  133. }
  134. }
  135. let p: Float
  136. if p0 == p1 {
  137. p = 0
  138. } else {
  139. p = lerp(t, inRange: p0...p1, outRange: 0...1)
  140. }
  141. let color0 = ARGB(c0)
  142. let color1 = ARGB(c1)
  143. return color0.interpolateTo(color1, p)
  144. }
  145. }
  146. // MARK: - Color Data
  147. fileprivate struct ARGB {
  148. let a: UInt8 = 0xff
  149. var r: UInt8
  150. var g: UInt8
  151. var b: UInt8
  152. }
  153. extension ARGB: Equatable {
  154. static func ==(lhs: ARGB, rhs: ARGB) -> Bool {
  155. return (lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b)
  156. }
  157. }
  158. extension ARGB {
  159. init(_ color: CGColor) {
  160. let c = color.components?.map { min(max($0, 0.0), 1.0) }
  161. switch color.numberOfComponents {
  162. case 2:
  163. self.init(r: UInt8((c?[0])! * 0xff), g: UInt8((c?[0])! * 0xff), b: UInt8((c?[0])! * 0xff))
  164. case 4:
  165. self.init(r: UInt8((c?[0])! * 0xff), g: UInt8((c?[1])! * 0xff), b: UInt8((c?[2])! * 0xff))
  166. default:
  167. self.init(r: 0, g: 0, b: 0)
  168. }
  169. }
  170. func interpolateTo(_ color: ARGB, _ t: Float) -> ARGB {
  171. let r = lerp(t, self.r, color.r)
  172. let g = lerp(t, self.g, color.g)
  173. let b = lerp(t, self.b, color.b)
  174. return ARGB(r: r, g: g, b: b)
  175. }
  176. }
  177. // MARK: - Utility
  178. fileprivate func lerp(_ t: Float, _ a: UInt8, _ b: UInt8) -> UInt8 {
  179. return UInt8(Float(a) + min(max(t, 0), 1) * (Float(b) - Float(a)))
  180. }
  181. fileprivate func lerp(_ value: Float, inRange: ClosedRange<Float>, outRange: ClosedRange<Float>) -> Float {
  182. return (value - inRange.lowerBound) * (outRange.upperBound - outRange.lowerBound) / (inRange.upperBound - inRange.lowerBound) + outRange.lowerBound
  183. }