gpt4 book ai didi

Swift 5.4 hex 到 NSColor

转载 作者:行者123 更新时间:2023-12-05 00:52:58 26 4
gpt4 key购买 nike

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

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

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

Convert Hex Color Code to NSColor

How to convert hex to 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)

可能不必使用 Cocoa。

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

你能帮帮我吗?

最佳答案

你可以试试这样的:

编辑:包括 toHex(alpha:),来 self 可能多年前从网上某处获得的代码。

EDIT3,4:包括#RRGGBBAA 的案例

编辑 5:去除十六进制字符串中的空格,使 NSColor (hex:"# 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 #

EDIT2:

您可以对 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)
}
}

关于Swift 5.4 hex 到 NSColor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68679658/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com