Skip to content

Instantly share code, notes, and snippets.

@proxpero
Created January 18, 2016 13:32
Show Gist options
  • Save proxpero/730edc59e1008276b200 to your computer and use it in GitHub Desktop.
Save proxpero/730edc59e1008276b200 to your computer and use it in GitHub Desktop.
An simple extension to NSColor to create a color from a six character RGB string. Written in Swift.
// Swift 2.2
extension NSColor {
convenience init(rgb: String) {
guard rgb.characters.count == 6 else { fatalError("Invalid rgb value: \(rgb)") }
let scanner = NSScanner(string: rgb)
var hexValue: UInt32 = 0
guard scanner.scanHexInt(&hexValue) else { fatalError("Scan hex \(rgb) error") }
self.init(
red: CGFloat((hexValue & 0xFF0000) >> 0x10) / 255.0,
green: CGFloat((hexValue & 0x00FF00) >> 0x01) / 255.0,
blue: CGFloat((hexValue & 0x0000FF) >> 0x00) / 255.0,
alpha: 1.0
)
}
}
@davejewell
Copy link

I believe that scanHextInt is now deprecated. And perhaps fatalError is a little brutal.

A more up to date implementation (Swift 5.8) might be as below. This is an extension on String, which I find more convenient.

var colorFromHexRGB: NSColor? {
    let scanner = Scanner(string: self)
    guard let hexValue = scanner.scanInt32(representation: .hexadecimal) else { return nil }
    let r = CGFloat((hexValue & 0xff0000) >> 16) / 255.0
    let g = CGFloat((hexValue & 0x00ff00) >> 8) / 255.0
    let b = CGFloat((hexValue & 0x0000ff) >> 0) / 255.0
    return NSColor.init(calibratedRed: r, green: g, blue: b, alpha: 1)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment