Skip to content

Commit 990c14b

Browse files
committed
NSColor.bestTextColorForBackgroundColor
1 parent 494f8ce commit 990c14b

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

ColorSetKit/NSColor+ColorSetKit.swift

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -148,17 +148,18 @@ import Cocoa
148148

149149
@objc class func bestTextColorForBackgroundColor( _ background: NSColor, lightTextColor: NSColor, darkTextColor: NSColor ) -> NSColor
150150
{
151-
guard let hsl = background.usingColorSpace( .sRGB )?.hsl() else
151+
guard var rgb = background.usingColorSpace( .sRGB )?.rgb() else
152152
{
153153
return NSColor.textColor
154154
}
155155

156-
if hsl.hue > 40.0 / 360.0 && hsl.hue < 180.0 / 360.0
157-
{
158-
return ( hsl.lightness > 0.3 ) ? darkTextColor : lightTextColor
159-
}
156+
rgb.red *= 255
157+
rgb.green *= 255
158+
rgb.blue *= 255
159+
160+
let contrast = ( ( rgb.red * 299 ) + ( rgb.green * 587 ) + ( rgb.blue * 114 ) ) / 1000
160161

161-
return ( hsl.lightness > 0.5 ) ? darkTextColor : lightTextColor
162+
return ( contrast > 123 ) ? darkTextColor : lightTextColor
162163
}
163164

164165
@objc var hexString: String

0 commit comments

Comments
 (0)