Skip to content

Instantly share code, notes, and snippets.

@phamquochoan
Created March 27, 2015 02:45
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 phamquochoan/4f83d66c70f335a5e999 to your computer and use it in GitHub Desktop.
Save phamquochoan/4f83d66c70f335a5e999 to your computer and use it in GitHub Desktop.
UIColor from hex code - Swift
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
let formattedCode = rgba.stringByReplacingOccurrencesOfString("#", withString: "")
let formattedCodeLength = count(formattedCode)
if formattedCodeLength != 3 && formattedCodeLength != 4 && formattedCodeLength != 6 && formattedCodeLength != 8 {
fatalError("invalid color")
}
var hexValue: UInt32 = 0
if NSScanner(string: formattedCode).scanHexInt(&hexValue) {
switch formattedCodeLength {
case 3:
red = CGFloat((hexValue & 0xF00) >> 8) / 15.0
green = CGFloat((hexValue & 0x0F0) >> 4) / 15.0
blue = CGFloat(hexValue & 0x00F) / 15.0
case 4:
red = CGFloat((hexValue & 0xF000) >> 12) / 15.0
green = CGFloat((hexValue & 0x0F00) >> 8) / 15.0
blue = CGFloat((hexValue & 0x00F0) >> 4) / 15.0
alpha = CGFloat(hexValue & 0x000F) / 15.0
case 6:
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
case 8:
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
default:
print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8")
}
}
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