How to convert UIColor to hex in Swift
Here’s a simple extension to convert a UIColor
to a hex string in Swift:
extension UIColor {
func toHex() -> String {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
assertionFailure("Failed to get RGBA components from UIColor")
return "#000000"
}
// Clamp components to [0.0, 1.0]
red = max(0, min(1, red))
green = max(0, min(1, green))
blue = max(0, min(1, blue))
alpha = max(0, min(1, alpha))
if alpha == 1 {
// RGB
return String(
format: "#%02lX%02lX%02lX",
Int(round(red * 255)),
Int(round(green * 255)),
Int(round(blue * 255))
)
} else {
// RGBA
return String(
format: "#%02lX%02lX%02lX%02lX",
Int(round(red * 255)),
Int(round(green * 255)),
Int(round(blue * 255)),
Int(round(alpha * 255))
)
}
}
}
Display P3 colors are truncated to fall within the sRGB gamut.
Usage
let color = UIColor(red: 0.5, green: 0.5, blue: 0.5, alpha: 1)
print(color.toHex()) // #808080