-
-
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.
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
/// 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