Skip to content

Commit b5908bd

Browse files
committed
Support for RGB hex in NSColor.
1 parent 7f336e5 commit b5908bd

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

ColorSetKit/NSColor+ColorSetKit.swift

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,35 @@ import Cocoa
173173
self.init( srgbRed: rgb.0, green: rgb.1, blue: rgb.2, alpha: alpha )
174174
}
175175

176+
@objc convenience init( hex: UInt, alpha: CGFloat = 1 )
177+
{
178+
let r = CGFloat( ( hex >> 16 ) & 0xFF )
179+
let g = CGFloat( ( hex >> 8 ) & 0xFF )
180+
let b = CGFloat( ( hex >> 0 ) & 0xFF )
181+
182+
self.init( srgbRed: r / 255, green: g / 255, blue: b / 255, alpha: alpha )
183+
}
184+
185+
@objc convenience init( hexString hex: String, alpha: CGFloat = 1 )
186+
{
187+
let s = hex.hasPrefix( "#" ) ? String( hex[ hex.index( after: hex.startIndex )... ] ) : hex
188+
189+
if s.count == 3
190+
{
191+
let r = String( s[ s.index( s.startIndex, offsetBy: 0 ) ] )
192+
let g = String( s[ s.index( s.startIndex, offsetBy: 1 ) ] )
193+
let b = String( s[ s.index( s.startIndex, offsetBy: 2 ) ] )
194+
195+
self.init( hexString: "\(r)\(r)\(g)\(g)\(b)\(b)", alpha: alpha )
196+
}
197+
else
198+
{
199+
let n = UInt( s, radix: 16 ) ?? 0
200+
201+
self.init( hex: n, alpha: alpha )
202+
}
203+
}
204+
176205
/**
177206
* Finds the best text color for a specific background color, to
178207
* ensure a good contrast ration between the text and the background

0 commit comments

Comments
 (0)