DynamicColor.swift 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. /*
  2. * DynamicColor
  3. *
  4. * Copyright 2015-present Yannick Loriot.
  5. * http://yannickloriot.com
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. *
  25. */
  26. #if os(iOS) || os(tvOS) || os(watchOS)
  27. import UIKit
  28. /**
  29. Extension to manipulate colours easily.
  30. It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
  31. */
  32. public typealias DynamicColor = UIColor
  33. #elseif os(OSX)
  34. import AppKit
  35. /**
  36. Extension to manipulate colours easily.
  37. It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
  38. */
  39. public typealias DynamicColor = NSColor
  40. #endif
  41. public extension DynamicColor {
  42. // MARK: - Manipulating Hexa-decimal Values and Strings
  43. /**
  44. Creates a color from an hex string (e.g. "#3498db"). The RGBA string are also supported (e.g. "#3498dbff").
  45. If the given hex string is invalid the initialiser will create a black color.
  46. - parameter hexString: A hexa-decimal color string representation.
  47. */
  48. convenience init(hexString: String) {
  49. let hexString = hexString.trimmingCharacters(in: .whitespacesAndNewlines)
  50. let scanner = Scanner(string: hexString)
  51. scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
  52. var color: UInt64 = 0
  53. if scanner.scanHexInt64(&color) {
  54. self.init(hex: color, useAlpha: hexString.count > 7)
  55. }
  56. else {
  57. self.init(hex: 0x000000)
  58. }
  59. }
  60. /**
  61. Creates a color from an hex integer (e.g. 0x3498db).
  62. - parameter hex: A hexa-decimal UInt64 that represents a color.
  63. - parameter alphaChannel: If true the given hex-decimal UInt64 includes the alpha channel (e.g. 0xFF0000FF).
  64. */
  65. convenience init(hex: UInt64, useAlpha alphaChannel: Bool = false) {
  66. let mask = UInt64(0xFF)
  67. let cappedHex = !alphaChannel && hex > 0xffffff ? 0xffffff : hex
  68. let r = cappedHex >> (alphaChannel ? 24 : 16) & mask
  69. let g = cappedHex >> (alphaChannel ? 16 : 8) & mask
  70. let b = cappedHex >> (alphaChannel ? 8 : 0) & mask
  71. let a = alphaChannel ? cappedHex & mask : 255
  72. let red = CGFloat(r) / 255.0
  73. let green = CGFloat(g) / 255.0
  74. let blue = CGFloat(b) / 255.0
  75. let alpha = CGFloat(a) / 255.0
  76. self.init(red: red, green: green, blue: blue, alpha: alpha)
  77. }
  78. /**
  79. Returns the color representation as hexadecimal string.
  80. - returns: A string similar to this pattern "#f4003b".
  81. */
  82. final func toHexString() -> String {
  83. return String(format: "#%06x", toHex())
  84. }
  85. /**
  86. Returns the color representation as an integer (without the alpha channel).
  87. - returns: A UInt32 that represents the hexa-decimal color.
  88. */
  89. final func toHex() -> UInt32 {
  90. let rgba = toRGBAComponents()
  91. return roundToHex(rgba.r) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.b)
  92. }
  93. /**
  94. Returns the RGBA color representation.
  95. - returns: A UInt32 that represents the color as an RGBA value.
  96. */
  97. func toRGBA() -> UInt32 {
  98. let rgba = toRGBAComponents()
  99. return roundToHex(rgba.r) << 24 | roundToHex(rgba.g) << 16 | roundToHex(rgba.b) << 8 | roundToHex(rgba.a)
  100. }
  101. /**
  102. Returns the AGBR color representation.
  103. - returns: A UInt32 that represents the color as an AGBR value.
  104. */
  105. func toAGBR() -> UInt32 {
  106. let rgba = toRGBAComponents()
  107. return roundToHex(rgba.a) << 24 | roundToHex(rgba.b) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.r)
  108. }
  109. // MARK: - Identifying and Comparing Colors
  110. /**
  111. Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal string.
  112. - parameter hexString: A hexa-decimal color number representation to be compared to the receiver.
  113. - returns: true if the receiver and the string are equals, otherwise false.
  114. */
  115. func isEqual(toHexString hexString: String) -> Bool {
  116. return self.toHexString() == hexString
  117. }
  118. /**
  119. Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal integer.
  120. - parameter hex: A UInt32 that represents the hexa-decimal color.
  121. - returns: true if the receiver and the integer are equals, otherwise false.
  122. */
  123. func isEqual(toHex hex: UInt32) -> Bool {
  124. return self.toHex() == hex
  125. }
  126. // MARK: - Querying Colors
  127. /**
  128. Determines if the color object is dark or light.
  129. It is useful when you need to know whether you should display the text in black or white.
  130. - returns: A boolean value to know whether the color is light. If true the color is light, dark otherwise.
  131. */
  132. func isLight() -> Bool {
  133. let components = toRGBAComponents()
  134. let brightness = ((components.r * 299.0) + (components.g * 587.0) + (components.b * 114.0)) / 1000.0
  135. return brightness >= 0.5
  136. }
  137. /**
  138. A float value representing the luminance of the current color. May vary from 0 to 1.0.
  139. We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20/#relativeluminancedef.
  140. */
  141. var luminance: CGFloat {
  142. let components = toRGBAComponents()
  143. let componentsArray = [components.r, components.g, components.b].map { (val) -> CGFloat in
  144. guard val <= 0.03928 else { return pow((val + 0.055) / 1.055, 2.4) }
  145. return val / 12.92
  146. }
  147. return (0.2126 * componentsArray[0]) + (0.7152 * componentsArray[1]) + (0.0722 * componentsArray[2])
  148. }
  149. /**
  150. Returns a float value representing the contrast ratio between 2 colors.
  151. We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20-TECHS/G18.html
  152. NB: the contrast ratio is a relative value. So the contrast between Color1 and Color2 is exactly the same between Color2 and Color1.
  153. - returns: A CGFloat representing contrast value.
  154. */
  155. func contrastRatio(with otherColor: DynamicColor) -> CGFloat {
  156. let otherLuminance = otherColor.luminance
  157. let l1 = max(luminance, otherLuminance)
  158. let l2 = min(luminance, otherLuminance)
  159. return (l1 + 0.05) / (l2 + 0.05)
  160. }
  161. /**
  162. Indicates if two colors are contrasting, regarding W3C's WCAG 2.0 recommendations.
  163. You can read it here: https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast
  164. The acceptable contrast ratio depends on the context of display. Most of the time, the default context (.Standard) is enough.
  165. You can look at ContrastDisplayContext for more options.
  166. - parameter otherColor: The other color to compare with.
  167. - parameter context: An optional context to determine the minimum acceptable contrast ratio. Default value is .Standard.
  168. - returns: true is the contrast ratio between 2 colors exceed the minimum acceptable ratio.
  169. */
  170. func isContrasting(with otherColor: DynamicColor, inContext context: ContrastDisplayContext = .standard) -> Bool {
  171. return self.contrastRatio(with: otherColor) > context.minimumContrastRatio
  172. }
  173. }