How to check if NSColor is light

Issue #627

Algorithm from https://www.w3.org/WAI/ER/WD-AERT/#color-contrast

1
2
3
4
5
6
7
8
9
10
11
extension NSColor {
var isLight: Bool {
guard
let components = cgColor.components,
components.count >= 3
else { return false }

let brightness = ((components[0] * 299) + (components[1] * 587) + (components[2] * 114)) / 1000
return brightness > 0.5
}
}

Then we can apply contrast color for our Text

1
2
3
4
5
6
7
8
9
10
extension Text {
func applyColorBaseOnBackground(_ color: NSColor?) -> some View {
guard let color = color else { return self }
if color.isMyLight {
return self.foregroundColor(Color.black)
} else {
return self
}
}
}

Comments