Skip to content

Instantly share code, notes, and snippets.

@gobijan
Created November 13, 2014 00:02
Show Gist options
  • Save gobijan/d724de27e2aff8131676 to your computer and use it in GitHub Desktop.
Save gobijan/d724de27e2aff8131676 to your computer and use it in GitHub Desktop.
Convert NSColor to Hex
func getHexFromColor(color: NSColor) -> NSString {
// Get the red, green, and blue components of the color
var r :CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
var rInt, gInt, bInt, aInt: Int
var rHex, gHex, bHex: NSString
var hexColor: NSString
color.getRed(&r, green: &g, blue: &b, alpha: &a)
// println("R: \(r) G: \(g) B:\(b) A:\(a)")
// Convert the components to numbers (unsigned decimal integer) between 0 and 255
rInt = Int((r * 255.99999))
gInt = Int((g * 255.99999))
bInt = Int((b * 255.99999))
// Convert the numbers to hex strings
rHex = NSString(format:"%2X", rInt)
gHex = NSString(format:"%2X", gInt)
bHex = NSString(format:"%2X", bInt)
hexColor = rHex+gHex+bHex
// println(rHex+gHex+bHex)
return hexColor
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment