Automatically determine the optimal font color by background color

Possible duplicate:
given the background color, how do I get the foreground color that makes it available for that background color?

It is interesting if there is any algorithm for determining the optimal font for readability by its background color.

For example: I create an icon with dynamic text and color. If the color is dark, I want the font color to be white, and if it is pretty bright, I want it to be black (or maybe even grayish).

public DynamicIcon( String iconText, Color backgroundColor ) { this.iconText = iconText; this.backgroundColor = backgroundColor; this.fontColor = determineFontColor( backgroundColor ); } //This is what I need (Pseudocode): private fontColor determineFontColor( Color backgroundColor ) { if( backgroundColor == bright ) return Color.BLACK; if( backgroundColor == dark ) return Color.WHITE; //If possible: if( backgroundColor == somethingInBetween ) return Color.GRAYISH; } 

Unfortunately, I did not find such an algorithm, although I am sure that it already exists. Does anyone have any ideas?

thanks ymene

+6
source share
1 answer

We should have done something similar in our system: based on the background, we color the black or white font. The solution we found is not perfect and in some rare cases chooses the wrong color, but we are very happy with it.

Here's what we did:

 int red = 0; int green = 0; int blue = 0; if ( backgroundColor.red + backgroundColor.green + backgroundColor.blue < 383 ) { red = 255; green = 255; blue = 255; } 

And then we use the values red , green and blue to create a new Color object.

The magic number 383 is the result of (255 + 255 + 255) / 2

+1
source

Source: https://habr.com/ru/post/905188/


All Articles