Skip to content

Instantly share code, notes, and snippets.

@jordangray
Forked from shadcn/gist:de147c42d7b3063ef7bc
Last active May 23, 2017 01:36
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 jordangray/036444e8e2c2c076f024ec2c192b07ef to your computer and use it in GitHub Desktop.
Save jordangray/036444e8e2c2c076f024ec2c192b07ef to your computer and use it in GitHub Desktop.
Convert a string representing a CSS hex colour to a UIColor in Swift.
/// Get the UIColor corresponding to a CSS hex color code (RGB[A] or RRGGBB[AA])
///
/// - Parameter hex: A hexadecimal representation of the colou
/// - Returns: The UIColor represented by the hexidecimal color code, or UIColor.clear if parsing failed
func colorFromHexString (hex:String) -> UIColor {
// Remove padding, leading hash symbol etc.
let hex = hex.trimmingCharacters(in: NSCharacterSet.alphanumerics.inverted)
// Get numeric representation
var int = UInt32()
guard Scanner(string: hex).scanHexInt32(&int) else {
return UIColor.clear
}
// Split into components
let r, g, b, a: UInt32
switch hex.characters.count {
case 3: // RGB
(r, g, b, a) = ((int >> 8) * 17, (int >> 4 & 0xf) * 17, (int & 0xf) * 17, 255)
case 4: // RGBA
(r, g, b, a) = ((int >> 12) * 17, (int >> 8 & 0xf) * 17, (int >> 4 & 0xf) * 17, (int & 0xf) * 17)
case 6: // RRGGBB
(r, g, b, a) = (int >> 16, int >> 8 & 0xff, int & 0xff, 255)
case 8: // RRGGBBAA
(r, g, b, a) = (int >> 24, int >> 16 & 0xff, int >> 8 & 0xff, int & 0xff)
default:
return UIColor.clear
}
return UIColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment