Function Repository Resource:

BlackWhiteContrast

Source Notebook

Pick black or white, depending on which gives the best contrast to a color

Contributed by: Jan Mangaldan

ResourceFunction["BlackWhiteContrast"][color]

returns Black or White, depending on which of the two gives the best contrast to the given color.

Examples

Basic Examples (2) 

Black gives good contrast with Pink:

In[1]:=
ResourceFunction["BlackWhiteContrast"][Pink]
Out[1]=

On the other hand, White gives good contrast with Magenta:

In[2]:=
ResourceFunction["BlackWhiteContrast"][Magenta]
Out[2]=

Scope (2) 

BlackWhiteContrast works on any color:

In[3]:=
ResourceFunction["BlackWhiteContrast"][XYZColor[1, 0, 1]]
Out[3]=

BlackWhiteContrast threads over lists:

In[4]:=
ResourceFunction["BlackWhiteContrast"][{Orange, Brown}]
Out[4]=

Applications (1) 

Demonstrate the contrast of black or white against a given color background:

In[5]:=
Manipulate[
 Graphics[{{col, Rectangle[]}, Text[Style["test", Bold, 90, ResourceFunction["BlackWhiteContrast"][col]], {0.5, 0.5}]}], {col, White}, SaveDefinitions -> True]
Out[5]=

Version History

  • 1.0.0 – 03 March 2021

Author Notes

BlackWhiteContrast uses the luma formula of ITU-R Recommendation BT.601 to pick a good contrasting shade. Support for other possible luma formulae (e.g. ITU-R Recommendation BT.709-6) will be added in a future update.

License Information