Last active
December 23, 2015 14:04
-
-
Save InsertNetan/4aa7f167704ec168b960 to your computer and use it in GitHub Desktop.
Swift extension for creating a UIColor from a hex string or number
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?(hexString userHexString: String, alpha: CGFloat) { | |
var hexString:String = userHexString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) | |
if (hexString.hasPrefix("#")) { | |
hexString = hexString.substringFromIndex(hexString.startIndex.advancedBy(1)) | |
} | |
let hexNum = CGFloat(strtoul(hexString, nil, 16)) | |
self.init(hex: hexNum, alpha: alpha) | |
} | |
convenience init?(hex: CGFloat, alpha: CGFloat) { | |
let mask = 0xff | |
let hex = Int(hex) | |
let red = CGFloat((hex >> 16) & mask) / 255 | |
let green = CGFloat((hex >> 08) & mask) / 255 | |
let blue = CGFloat((hex >> 00) & mask) / 255 | |
self.init(red: red, green: green , blue: blue, alpha: alpha) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment