I am developing a program for macOS.
I need to convert a hex color to NSColor.
I looked at the proposed solutions here:
Convert Hex Color Code to NSColor
How to convert hex to NSColor?
But none of it works correctly with Xcode 12.5.1.
At the moment I did this, it works correctly:
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)
Possibly not having to use Cocoa.
I would like a function like this: hexToNSColor("#2196f3")
Can you give me a hand?
you could try something like this:
EDIT: included toHex(alpha:), from code I probably got from the net somewhere many years ago.
EDIT3,4: included the case for #RRGGBBAA
EDIT 5: stripping blank spaces in the hex string, to make NSColor (hex:" # 2196f380 ") work as well.
EDIT2:
you can do the same for UIColor, and for Color (with UIColor or NSColor):