Created
January 18, 2016 13:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.