I am writing a program log window, messages of different colors are displayed depending on the type of message. Periodically there is such a combination of colors that the text is difficult to read. I want to dynamically change the color of the text depending on the background color so that it is not problematic to perceive the information.

There are two colors represented in RGB (Color). The first color is the text color, the second color is the background color. How can I programmatically understand that the text color will be difficult to distinguish on the background color? .. It seems to me that there is a fairly simple solution, but I can’t think of it ... compare in these colors so that 100% can say: "Yes, there will be no difficulty in reading the text."

  • Enough to translate into grayscale. Red on blue will be bad. yellow on black is good. - Yura Ivanov

2 answers 2

I think the easiest way is to take the lengths of the background and text color vectors (SQRT (R ^ 2 + b ^ 2 + G ^ 2)) and subtract them from each other - if the difference is small, then it’s hard to see. You can probably still overtake in monochrome (there is approximately as long only with certain coefficients based on the perception of the color of the eye) and also check.

  • SQRT (R ^ 2 + b ^ 2-G ^ 2) namely (-G ^ 2) ... just in this case there can be an exceptional situation of the root of a negative number ... I was also offered (Brightness1 - Brightness2) / Brightness1. .. (i.e., to compare something similar to the contrast of these colors), but in this case, division by zero may also turn out. Brightness1 may be zero for black. - pincher1519
  • @ pincher1519, Plus, of course, was sealed, regarding division by zero - a special situation, it is possible to handle a separate case. - Chad
  • You can also use the W3C Color Readability, based on the translation into the YIQ color space.

Color visibility can be determined according to the following algorithm:

The colors between the two colors are greater than a set range.

Color brightness is determined by the following formula: ((Red value X 299) + (Green value X 587) + (Blue value X 114)) / 1000

Note: This algorithm is taken from a RGB values ​​for YIQ values. This brightness value gives a perceived brightness for a color.

Color difference: (maximum (Red value 1, Red value 2) - minimum (Red value 1, Red value 2)) + (maximum (Green value 1, Green value 2) - minimum (Green value 1, Green value 2)) + (maximum (Blue value 1, Blue value 2) - minimum (Blue value 1, Blue value 2))

The range for color brightness difference is 125. The range for color difference is 500.