Search code examples
iosswiftiphoneuikituicolor

Hex color code with opacity is not working as expected in iOS


I am programmatically setting the hex color with alpha but result is not looking as expected. Example: hex color #478295 with opacity 50% which is #80478295 and I am using `

public convenience init?(hex: String) {
    let r, g, b, a: CGFloat
    
    if hex.hasPrefix("#") {
        let start = hex.index(hex.startIndex, offsetBy: 1)
        let hexColor = String(hex[start...])
        
        if hexColor.count == 8 {
            let scanner = Scanner(string: hexColor)
            var hexNumber: UInt64 = 0
            
            if scanner.scanHexInt64(&hexNumber) {
                r = CGFloat((hexNumber & 0xff000000) >> 24) / 255
                g = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
                b = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
                a = CGFloat(hexNumber & 0x000000ff) / 255
                self.init(red: r, green: g, blue: b, alpha: a)
                return
            }
        }
    }
    
    return nil
}
`

Expected: Red: 0.277, green: 0.511, blue: 0.583, alpha: 0.5

Actual: red 0.5019607843137255 green 0.2784313725490196 blue 0.5098039215686274 alpha 0.5843137254901961

Expected result enter image description here Actual result enter image description here

Xcode: 13.2.1


Solution

  • In your question you put the alpha at the first 8 bits, not the last. So it goes like this:

    a = CGFloat((hexNumber & 0xff000000) >> 24) / 255
    r = CGFloat((hexNumber & 0x00ff0000) >> 16) / 255
    g = CGFloat((hexNumber & 0x0000ff00) >> 8) / 255
    b = CGFloat(hexNumber & 0x000000ff) / 255