Skip to content

Instantly share code, notes, and snippets.

@streetturtle
Last active December 24, 2021 01:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save streetturtle/ba837c790c1276ecb6e8f63df5bb89bb to your computer and use it in GitHub Desktop.
Save streetturtle/ba837c790c1276ecb6e8f63df5bb89bb to your computer and use it in GitHub Desktop.
Useful NSColorExtensions
extension NSColor {
/// NSColor initializer accepting hex color string
///
/// ```
/// NSColor(hex: "#BADA55")
/// ```
///
/// - Parameter hex: Hex color string, may include a hash (#) prefix
/// - Returns: an NSColor of given hex color string
convenience init (hex: String) {
var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if (cString.hasPrefix("#")) {
cString.remove(at: cString.startIndex)
}
if ((cString.count) != 6) {
self.init(.gray)
}
var rgbValue:UInt64 = 0
Scanner(string: cString).scanHexInt64(&rgbValue)
self.init(
red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment