c# – How to programmatically understand that the text of a given color will be difficult to read on the selected background color?

Question:

I am writing a program log window, messages of different colors are displayed depending on the type of message. From time to time 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 to programmatically understand that the color of the text will be difficult to distinguish on the background color? .. It seems to me there is a fairly simple solution, but I just can't think of it … I'll choose the threshold empirically to change the color of the text, but I can't understand what is needed compare in these colors so that 100% can say: "Yes, there will be no difficulty in reading the text."

Answer:

  • You can also use the W3C Color Readability, guidelines based on the YIQ color space translation .

Color visibility can be determined according to the following algorithm:

Two colors provide good color visibility if the brightness difference and the color difference 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 formula for converting RGB values ​​to YIQ values. This brightness value gives a perceived brightness for a color.

Color difference is determined by the following formula: (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.

Scroll to Top