On one of pages we're currently working on users can change the background of the text displayed.
We would like to automatically alter the foreground colour to maintain reasonable contrast of the text.
We would also prefer the colour range to be discretionary. For example, if background is changing from white to black in 255 increments, we don't want to see 255 shades of foreground colour. In this scenario, perhaps 2 to 4, just to maintain reasonable contrast.
Any UI/design/colour specialists/painters out there to whip out the formula?
In terms of sheer readability, you want to use black and white text on whatever background it is. So convert RGB to HSV, and just check whether V is < 0.5. If so, white, if not, black.
Try that first and see if you find it attractive.
If you don't, then you probably want the white and black not to be so stark when your background is too bright or too dark. To tone this down, keep the same hue and saturation, and use these values for brightness:
background V foreground V
0.0-0.25 0.75
0.25-0.5 1.0
0.5-0.75 0.0
0.75-1.0 0.25
On a medium color, you'll still see black or white text which will be nicely readable. On a dark color or light color, you'll see the same color text but at least 3/4 away in terms of brightness and therefore still readable. I hope it looks nice :)