How do I convert a UIColor to a hexadecimal string?

Viewed 11224

I have a project where I need to store the RGBA values of a UIColor in a database as an 8-character hexadecimal string. For example, [UIColor blueColor] would be @"0000FFFF". I know I can get the component values like so:

CGFloat r,g,b,a;
[color getRed:&r green:&g blue: &b alpha: &a];

but I don't know how to go from those values to the hex string. I've seen a lot of posts on how to go the other way, but nothing functional for this conversion.

3 Answers

Swift 4 answer by extension UIColor:

extension UIColor {
    var hexString: String {
        let colorRef = cgColor.components
        let r = colorRef?[0] ?? 0
        let g = colorRef?[1] ?? 0
        let b = ((colorRef?.count ?? 0) > 2 ? colorRef?[2] : g) ?? 0
        let a = cgColor.alpha

        var color = String(
            format: "#%02lX%02lX%02lX",
            lroundf(Float(r * 255)),
            lroundf(Float(g * 255)),
            lroundf(Float(b * 255))
        )
        if a < 1 {
            color += String(format: "%02lX", lroundf(Float(a)))
        }
        return color
    }
}
Related