Get Foreground Color
Determines a suitable foreground color (black or white) for optimal contrast against the specified background color.
The function calculates the relative luminance of the background color using the formula: 0.299 * R + 0.587 * G + 0.114 * B . This ensures the foreground text remains readable regardless of background brightness.
VB
Public Function GetForegroundColor(backgroundColor As Color) As Color
'Calculate the perceived luminance (using the relative luminance formula)
Dim luminance As Double = (0.299 * backgroundColor.R + 0.587 * backgroundColor.G + 0.114 * backgroundColor.B) / 255
'If the brightness is greater than 0.5, use black; otherwise, use white.
If luminance > 0.5 Then
Return Color.Black
Else
Return Color.White
End If
End Function