Swift 5.4 十六进制转 NSColor

Pau*_*aul 3 macos hex nscolor swift

我正在为 macOS 开发一个程序。

我需要将十六进制颜色转换为 NSColor。

我在这里查看了建议的解决方案:

将十六进制颜色代码转换为 NSColor

如何将十六进制转换为 NSColor?

但这些都不能在 Xcode 12.5.1 上正常工作。

目前我这样做,它工作正常:

extension NSObject {
    func RGB(r:CGFloat, g:CGFloat, b:CGFloat, alpha:CGFloat? = 1) -> NSColor {
        return NSColor(red: r/255, green: g/255, blue: b/255, alpha: alpha!)
    }
}

let fillColor = RGB(r: 33, g: 150, b: 243)
Run Code Online (Sandbox Code Playgroud)

可能不必使用可可。

我想要一个这样的函数:hexToNSColor("#2196f3")

你能帮我个忙吗?

wor*_*dog 9

你可以尝试这样的事情:

编辑:包括 toHex(alpha:),来自我多年前可能从网络上得到的代码。

EDIT3,4:包括 #RRGGBBAA 的情况

编辑5:去掉十六进制字符串中的空格,使 NSColor (十六进制:“# 2196f380”)也能工作。

extension NSColor {
    
 convenience init(hex: String) {
    let trimHex = hex.trimmingCharacters(in: .whitespacesAndNewlines)
    let dropHash = String(trimHex.dropFirst()).trimmingCharacters(in: .whitespacesAndNewlines)
    let hexString = trimHex.starts(with: "#") ? dropHash : trimHex
    let ui64 = UInt64(hexString, radix: 16)
    let value = ui64 != nil ? Int(ui64!) : 0
    // #RRGGBB
    var components = (
        R: CGFloat((value >> 16) & 0xff) / 255,
        G: CGFloat((value >> 08) & 0xff) / 255,
        B: CGFloat((value >> 00) & 0xff) / 255,
        a: CGFloat(1)
    )
    if String(hexString).count == 8 {
        // #RRGGBBAA
        components = (
            R: CGFloat((value >> 24) & 0xff) / 255,
            G: CGFloat((value >> 16) & 0xff) / 255,
            B: CGFloat((value >> 08) & 0xff) / 255,
            a: CGFloat((value >> 00) & 0xff) / 255
        )
    }
    self.init(red: components.R, green: components.G, blue: components.B, alpha: components.a)
}

func toHex(alpha: Bool = false) -> String? {
    guard let components = cgColor.components, components.count >= 3 else {
        return nil
    }
    
    let r = Float(components[0])
    let g = Float(components[1])
    let b = Float(components[2])
    var a = Float(1.0)
    
    if components.count >= 4 {
        a = Float(components[3])
    }
    
    if alpha {
        return String(format: "%02lX%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255), lroundf(a * 255))
    } else {
        return String(format: "%02lX%02lX%02lX", lroundf(r * 255), lroundf(g * 255), lroundf(b * 255))
    }
}
}
 
    let nscol = NSColor(hex: "#2196f3")  // <-- with or without #
Run Code Online (Sandbox Code Playgroud)

编辑2:

您可以对 UIColor 和 Color (使用 UIColor 或 NSColor)执行相同的操作:

extension Color {
    public init(hex: String) {
        self.init(UIColor(hex: hex))
    }

    public func toHex(alpha: Bool = false) -> String? {
        UIColor(self).toHex(alpha: alpha)
    }
}
Run Code Online (Sandbox Code Playgroud)