Skip to content

Instantly share code, notes, and snippets.

@a-eid
Last active April 7, 2018 06:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a-eid/583f04dee0cdca3dafa762875ff80941 to your computer and use it in GitHub Desktop.
Save a-eid/583f04dee0cdca3dafa762875ff80941 to your computer and use it in GitHub Desktop.
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let r = CGFloat((hex >> 16) & 0xff) / 255
let g = CGFloat((hex >> 08) & 0xff) / 255
let b = CGFloat((hex >> 00) & 0xff) / 255
self.init(red: r, green: g, blue: b, alpha: alpha)
} }
// usage
let color = UIColor(hex: 0xff00cc, alpha: 1.0)
let color2 = UIColor(hex: 0xff00cc) // alpha of 1 is the default
extension UIColor {
convenience init(hexCode: String) {
let hex =
hexCode.stringByTrimmingCharactersInSet(NSCharacterSet.alphanumericCharacterSet().invertedSet)
var int = UInt32()
NSScanner(string: hex).scanHexInt(&int)
let a, r, g, b: UInt32
switch hex.characters.count {
case 3:
(a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
case 6:
(a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
case 8:
(a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 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)
} }
let color = UIColor("#80FFFFFF")
let color = UIColor("#FFFFFF")
let color = UIColor("#FFF")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment