Skip to content

Instantly share code, notes, and snippets.

@aqubi
Last active November 12, 2021 06:46
Show Gist options
  • Save aqubi/e1ac6b6e37279ec576616518ed69ba41 to your computer and use it in GitHub Desktop.
Save aqubi/e1ac6b6e37279ec576616518ed69ba41 to your computer and use it in GitHub Desktop.
func toHexString1(_ color:UIColor) -> String? {
guard let components = color.cgColor.components else { return nil }
return toHexString(components)
}
func toHexString2(_ color:UIColor) -> String? {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
guard color.getRed(&r, green: &g, blue: &b, alpha: &a) else { return nil }
return toHexString([r, g, b, a])
}
func toHexString3(_ color:UIColor) -> String? {
let ciColor = CIColor(cgColor: color.cgColor)
return toHexString([ciColor.red, ciColor.green, ciColor.blue, ciColor.alpha])
}
func toHexString(_ components:[CGFloat]) -> String? {
if components.count < 3 { return nil }
let r = Float(components[0])
let g = Float(components[1])
let b = Float(components[2])
let a = components.count >= 4 ? Float(components[3]) : 1.0
if a != 1 {
return String(format: "#%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
} else {
return String(format: "#%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment