Last active
April 21, 2016 12:08
-
-
Save cocoaNib/8e8bae4be1ee835e750f6f54a3e77dc6 to your computer and use it in GitHub Desktop.
UIColor Extension - supporting long + short hex format and alpha
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
extension UIColor { | |
convenience init(hex: String, alpha: CGFloat = 1) { | |
let scanner = NSScanner(string: hex) | |
scanner.charactersToBeSkipped = NSCharacterSet(charactersInString: "#") | |
var hexInt: UInt32 = 0 | |
if scanner.scanHexInt(&hexInt) { | |
if hex.characters.count < 6 { | |
let red = CGFloat((hexInt & 0xF00) >> 8) / 15.0 | |
let green = CGFloat((hexInt & 0x0F0) >> 4) / 15.0 | |
let blue = CGFloat( hexInt & 0x00F) / 15.0 | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} else { | |
let red = CGFloat((hexInt & 0xFF0000) >> 16) / 255.0 | |
let green = CGFloat((hexInt & 0x00FF00) >> 8) / 255.0 | |
let blue = CGFloat( hexInt & 0x0000FF) / 255.0 | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
} else { | |
print("UIColor Error: Scan hex error -> returning ClearColor") | |
self.init(white: 0.0, alpha: 0.0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment