Created
February 17, 2020 05:42
-
-
Save dagronf/ec94b9dc08d239c7ef7577057ebaa670 to your computer and use it in GitHub Desktop.
Returns a contrasting NSColor for this NSColor. Useful for putting text on a plain color background or the like...
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension NSColor { | |
private struct ColorComponents { | |
var r: CGFloat = 0.0 | |
var g: CGFloat = 0.0 | |
var b: CGFloat = 0.0 | |
var a: CGFloat = 0.0 | |
} | |
private func components() -> ColorComponents { | |
var result = ColorComponents() | |
self.getRed(&result.r, green: &result.g, blue: &result.b, alpha: &result.a) | |
return result | |
} | |
func contrastingTextColor() -> NSColor { | |
if self == NSColor.clear { | |
return .black | |
} | |
guard let c1 = self.usingColorSpace(.deviceRGB) else { | |
return .black | |
} | |
let rgbColor = c1.components() | |
// Counting the perceptive luminance - human eye favors green color... | |
let avgGray: CGFloat = 1 - (0.299 * rgbColor.r + 0.587 * rgbColor.g + 0.114 * rgbColor.b) | |
return avgGray > 0.5 ? .white : .black | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment