Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
extension UIColor{
convenience init (hexString:String) {
let cleanString = hexString.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var rgbValue = UInt32()
NSScanner(string: cleanString).scanHexInt(&rgbValue)
let a,r,g,b:UInt32
switch cleanString.characters.count{
case 3: // RGB (12-bit)
(a, r, g, b) = (255, (rgbValue >> 8) * 17, (rgbValue >> 4 & 0xF) * 17, (rgbValue & 0xF) * 17)
case 6: // RGB (24-bit)
(a, r, g, b) = (255, rgbValue >> 16, rgbValue >> 8 & 0xFF, rgbValue & 0xFF)
case 8: // ARGB (32-bit)
(a, r, g, b) = (rgbValue >> 24, rgbValue >> 16 & 0xFF, rgbValue >> 8 & 0xFF, rgbValue & 0xFF)
default:
(a, r, g, b) = (1, 1, 1, 0)
}
self.init(
red: CGFloat(r)/255,
green: CGFloat(g)/255,
blue: CGFloat(b)/255,
alpha: CGFloat(a)/255)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment