Programmatically choose high-contrast colors
You need a difference in brightness for text to be readable, as color vision itself has too low resolution.
So as an algorithm I'd suggest the following:
Pick a random background color.
Then decide whether it is a light or a dark color. For example you could check whether the average of the three primary colors is greater or equal 128.
For a light color use black text, for a dark one white text.
Update: Here is an example image I made while playing with the split_evenly
example of the Rust crate plotters
. It shows the colors in Palette99
:
"Contrast" is a loaded word. If you just care about being able to read the text, then one easy way is to work in a luminance-based color space like HSL, and pick foreground and background colors with big differences in luminance.
The conversion between HSL and RGB is well-known--see Wikipedia for the details.
If you're talking about actual color contrast, it's not nearly as cut-and-dried (there are a lot of perceptual factors that, as far as I know, haven't been reduced to a single colors space), but I suspect you don't need that level of sophistication.
Check out this PHP solution: Calculating Color Contrast with PHP by Andreas Gohr. It can be ported to any language of course.
He also has a very nice demonstration of his contrast analyzer where you can find some minimal contrast levels to work with.