Skip to content

Commit 494f8ce

Browse files
committed
NSColor.bestTextColorForBackgroundColor
1 parent 7eaaada commit 494f8ce

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

ColorSet/Classes/PaletteColorItem.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ import ColorSetKit
6666
rect.fill()
6767

6868
let hsl = base.hsl()
69-
let textColor = ( hsl.lightness >= 0.5 ) ? NSColor.black : NSColor.white
69+
let textColor = NSColor.bestTextColorForBackgroundColor( base )
7070
var p = NSMakePoint( rect.origin.x + 10, rect.origin.y + 10 )
7171

7272
( info.name as NSString ).draw( at: p, withAttributes: [ .foregroundColor : textColor, .font : NSFont.systemFont( ofSize: 25, weight: .thin ) ] )

ColorSetKit/NSColor+ColorSetKit.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,26 @@ import Cocoa
141141
self.init( srgbRed: rgb.0, green: rgb.1, blue: rgb.2, alpha: alpha )
142142
}
143143

144+
@objc class func bestTextColorForBackgroundColor( _ background: NSColor ) -> NSColor
145+
{
146+
return NSColor.bestTextColorForBackgroundColor( background, lightTextColor: NSColor.white, darkTextColor: NSColor.black )
147+
}
148+
149+
@objc class func bestTextColorForBackgroundColor( _ background: NSColor, lightTextColor: NSColor, darkTextColor: NSColor ) -> NSColor
150+
{
151+
guard let hsl = background.usingColorSpace( .sRGB )?.hsl() else
152+
{
153+
return NSColor.textColor
154+
}
155+
156+
if hsl.hue > 40.0 / 360.0 && hsl.hue < 180.0 / 360.0
157+
{
158+
return ( hsl.lightness > 0.3 ) ? darkTextColor : lightTextColor
159+
}
160+
161+
return ( hsl.lightness > 0.5 ) ? darkTextColor : lightTextColor
162+
}
163+
144164
@objc var hexString: String
145165
{
146166
let rgb = self.rgb()

0 commit comments

Comments
 (0)