Last active
November 12, 2021 06:46
-
-
Save aqubi/e1ac6b6e37279ec576616518ed69ba41 to your computer and use it in GitHub Desktop.
This file contains 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
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