Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically determine optimal fontcolor by backgroundcolor [duplicate]

Possible Duplicate:
given a background color, how to get a foreground color that make it readable on that background color?

I wonder, if there is any algorithm to determine the optimal fontcolor for readability by its background color.

For example: I create an icon with dynamic text and color. If the color is kinda dark, I want it to set the font color to white and if its fairly bright, I want it to be in 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;
  }

Unfortunatly I didnt find any algorithm like that, eventhough I am kinda sure, that it already exists. Anyone has any ideas?

thanks, ymene

like image 909
crusam Avatar asked Jan 05 '12 11:01

crusam


1 Answers

We had to do something like that on our system: based on the background, we colour the font black or white. The solution we found is not perfect and chooses the wrong colour on some rare occasions, but we are very satisfied with it.

This is 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 red, green and blue values to create a new Color object.

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

like image 80
Mario Marinato Avatar answered Oct 20 '22 13:10

Mario Marinato