Search code examples
swiftswiftuihexrgb

Hex codes/RGB values for SwiftUI colors?


is there a compiled list of hex codes or RGB values for SwiftUI colors? I'd like to know either for Color.purple but can't seem to find any good sources. Is there a way to programmatically determine the hex code or RGB value? Or maybe I can look at some properties of Color? Thanks in advance!


Solution

  • If you are coding in SwiftUI 2 you can convert your Color to UIColor and use getRed method to get the red, green, blue and alpha components. Once you have the components you can convert the values to hexa string:


    extension Color {
        var uiColor: UIColor { .init(self) }
        typealias RGBA = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
        var rgba: RGBA? {
            var (r, g, b, a): RGBA = (0, 0, 0, 0)
            return uiColor.getRed(&r, green: &g, blue: &b, alpha: &a) ? (r, g, b, a) : nil
        }
        var hexaRGB: String? {
            guard let (red, green, blue, _) = rgba else { return nil }
            return String(format: "#%02x%02x%02x",
                Int(red * 255),
                Int(green * 255),
                Int(blue * 255))
        }
        var hexaRGBA: String? {
            guard let (red, green, blue, alpha) = rgba else { return nil }
            return String(format: "#%02x%02x%02x%02x",
                Int(red * 255),
                Int(green * 255),
                Int(blue * 255),
                Int(alpha * 255))
        }
    }
    

    Color.purple.hexaRGB     // "#af52de"
    Color.purple.hexaRGBA    // "#af52deff"
    if let (red, green, blue, alpha) = Color.purple.rgba {
        red   // 0.686274528503418
        green // 0.321568638086319
        blue  // 0.8705882430076599
        alpha // 1
    }