SwiftUI - hex颜色不正确



我已经写了一个扩展转换十六进制的颜色。增加了断点来检查r,g,b值是否正确。一切看起来都很好,但是当我初始化颜色时,它与我提供的十六进制值不一样。

extension Color {
init(hexColor: String) {
// Trim all characters excepts Alphanumerics
let hex = hexColor.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
let hexNumber = Int(hex, radix: 16) ?? 0
let redColor: Double = Double((hexNumber >> 16) & 0xFF)
let greenColor: Double = Double((hexNumber >> 8) & 0xFF)
let blueColor: Double = Double((hexNumber >> 0) & 0xFF)
self.init(.sRGB, red: redColor, green: greenColor, blue: blueColor, opacity: 1)
} }

使用的初始化和颜色空间接受0…1 .颜色值。除以255

解决方案:


extension Color {
init(hexColor: String) {
// Trim all characters excepts Alphanumerics
let hex = hexColor.filter(.isHexDigit)
let hexNumber = Int(hex, radix: 16) ?? 0
let redColor: Double = Double((hexNumber >> 16) & 0xFF) / 255
let greenColor: Double = Double((hexNumber >> 8) & 0xFF) / 255
let blueColor: Double = Double((hexNumber >> 0) & 0xFF) / 255
self.init(.sRGB, red: redColor, green: greenColor, blue: blueColor, opacity: 1)
}
}

相关内容

  • 没有找到相关文章

最新更新