How to create UIColor from hex value?

How do I create a UIColor object of a certain color that I have the hex value for?

Accepted Reply

Shinehah,


here's a possible answer to what i think you're asking about, created in a Playground (which means it uses AppKit and NSColor instead of UIKit and UIColor).


example: the hex color spec for aquamarine is #7FFFD4, or rgb(127,255,212), so we can use the following code


import AppKit

let redPercentage = CGFloat(0x7F)/255
let greenPercentage = CGFloat(0xFF)/255
let bluePercentage = CGFloat(0xD4)/255

let aquamarineColor = NSColor(red: redPercentage, green: greenPercentage, blue: bluePercentage, alpha: 1.0)


the arguments for NSColor must be between 0.0 and 1.0. the values (percentages) above come out to 127/255, 255/255, and 212/255, or about 0.498, 1.0, and 0.831, respectively (and then 1.0 for the alpha/transparency amount).


hope that helps,

DMG

Replies

Shinehah,


here's a possible answer to what i think you're asking about, created in a Playground (which means it uses AppKit and NSColor instead of UIKit and UIColor).


example: the hex color spec for aquamarine is #7FFFD4, or rgb(127,255,212), so we can use the following code


import AppKit

let redPercentage = CGFloat(0x7F)/255
let greenPercentage = CGFloat(0xFF)/255
let bluePercentage = CGFloat(0xD4)/255

let aquamarineColor = NSColor(red: redPercentage, green: greenPercentage, blue: bluePercentage, alpha: 1.0)


the arguments for NSColor must be between 0.0 and 1.0. the values (percentages) above come out to 127/255, 255/255, and 212/255, or about 0.498, 1.0, and 0.831, respectively (and then 1.0 for the alpha/transparency amount).


hope that helps,

DMG