Created
December 11, 2016 01:53
-
-
Save alfian0/0148b318fa9d7d1a9b8c998c10b87eba to your computer and use it in GitHub Desktop.
Swift UIColor Utils
This file contains 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 { | |
public convenience init(hex: String) { | |
let characterSet = NSCharacterSet.whitespaceAndNewlineCharacterSet().mutableCopy() as! NSMutableCharacterSet | |
characterSet.formUnionWithCharacterSet(NSCharacterSet(charactersInString: "#")) | |
let cString = hex.stringByTrimmingCharactersInSet(characterSet).uppercaseString | |
if (cString.characters.count != 6) { | |
self.init(white: 1.0, alpha: 1.0) | |
} else { | |
var rgbValue: UInt32 = 0 | |
NSScanner(string: cString).scanHexInt(&rgbValue) | |
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, | |
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, | |
blue: CGFloat(rgbValue & 0x0000FF) / 255.0, | |
alpha: CGFloat(1.0)) | |
} | |
} | |
public convenience init(hex: UInt32, alpha: CGFloat) { | |
let red = CGFloat((hex & 0xFF0000) >> 16)/256.0 | |
let green = CGFloat((hex & 0xFF00) >> 8)/256.0 | |
let blue = CGFloat(hex & 0xFF)/256.0 | |
self.init(red: red, green: green, blue: blue, alpha: alpha) | |
} | |
public convenience init(red: Int, green: Int, blue: Int) { | |
let newRed = CGFloat(red) / 255 | |
let newGreen = CGFloat(green) / 255 | |
let newBlue = CGFloat(blue) / 255 | |
self.init(red: newRed,green: newGreen, blue: newBlue, alpha: 1.0) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment