Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading