[英]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.我正在以编程方式使用 alpha 设置十六进制颜色,但结果看起来不像预期的那样。 Example: hex color #478295 with opacity 50% which is #80478295 and I am using `
示例:十六进制颜色 #478295,不透明度为 50%,即 #80478295,我正在使用 `
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预期:红色:0.277,绿色:0.511,蓝色:0.583,alpha:0.5
Actual: red 0.5019607843137255 green 0.2784313725490196 blue 0.5098039215686274 alpha 0.5843137254901961实际:红色 0.5019607843137255 绿色 0.2784313725490196 蓝色 0.5098039215686274 alpha 0.5843137254901961
Expected result预期结果
Actual result
实际结果
Xcode: 13.2.1 Xcode:13.2.1
In your question you put the alpha at the first 8 bits, not the last.在您的问题中,您将 alpha 放在前 8 位,而不是最后一位。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.