Skip to content

Instantly share code, notes, and snippets.

@youn9k
Created April 3, 2023 11:17
Show Gist options
  • Save youn9k/4f28e8a037b96661a9d158a542ed9990 to your computer and use it in GitHub Desktop.
Save youn9k/4f28e8a037b96661a9d158a542ed9990 to your computer and use it in GitHub Desktop.
hex string to UIColor
public extension UIColor {
/// "#RRGGBB", "#RRGGBBAA"
convenience init?(hex: String) {
var hexString = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
if hexString.hasPrefix("#") {
hexString.remove(at: hexString.startIndex)
}
guard hexString.count == 6 || hexString.count == 8 else {
return nil
}
let scanner = Scanner(string: hexString)
var rgbValue: UInt64 = 0
guard scanner.scanHexInt64(&rgbValue) else {
return nil
}
let red, green, blue, alpha: CGFloat
if hexString.count == 6 {
red = CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(rgbValue & 0x0000FF) / 255.0
alpha = 1.0
} else {
red = CGFloat((rgbValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((rgbValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((rgbValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(rgbValue & 0x000000FF) / 255.0
}
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