I need to generate a random background color that's visually pleasing for three types of text color: ARGB(255,255,255,255)
, ARGB(63,255,255,255)
, and ARGB(255,0,0,0)
. The colors are white, white at 0.25 opacity, and black. I have yet to see an example on SO or somewhere else that compares a color against multiple colors to decide if there is good contrast between them (The comparison is done between two colors only). I don't fully understand color theory, so I'm looking for help.
Random background color for multiple foreground colors
841 Views Asked by Mark13426 At
2
There are 2 best solutions below
0

Contrasting colors to white are any dark. On other hand, contrasting colors to black are any light. So it's difficult to choose a contrasting color to both white and black.
It may be some average gray color or any other color with the same brightness.
The brightness may be calculated with this formula:
int brightness = (int)(0.30 * red + 0.59 * green + 0.11 * blue);
Let's fix the brightness
value to average (i.e. 128), and randomly select red
and green
values. Then we can calculate blue
:
var random = new Random();
var red = random.Next(128);
var green = random.Next(128);
var blue = (int)(128 - 0.30 * red - 0.59 * green);
The resulting color is quite contrasting to both black and white.
Firstly you need to get yourself familiar with color spaces and decide what will make a random color visually appealing. A color basically can be represented as three components in many different spaces. The preferred representation for computers is RGB with is the amount of red, green and blue that conforms the color. However, for the human eye the HSV (hue, saturation, value) is probably easier to understand. In this color space the saturation represents how 'saturated' is the color, i.e. the gray scale range has a saturation of zero since it really doesn't represent a color. The value (or intensity) think of it as the brightness and the hue sort of gives you the in what direction of the spectrum (think on a rainbow) the color belong. The alpha value is not part of the color itself, it rather specify how a particular color mixes with the background (i.e. the resulting color is calculated as the weighted sum of the front color by its alpha component and the background color)
Now in terms of selecting a visually appealing color that is more complicated and depends more on each individual taste. You normally achieve a high contrast color by selecting another color whose distance in HSV color space is big enough. In fact, selecting a color with one of the two components the same (e.g. same saturation and intensity) but very different hue will give you a color that will make high contrast with the original one. The conversion formulas from RGB to HSV and viceversa can be found here. Hope this helps.