0

I am currently developing an App. In this App I get some RGB color code from the server, that I want to display.

As the color I get should be the background color of a Label, there is some text, that should be displayed above it. The user defining the color is completely free in choosing a color, so I am in need of finding an algorithm, where the text color of the label is somehow contrasted to the color I get from the webservice.

Problem explained in an example:

  • I choose black 0x000000 to be the textcolor. If the user defines a color like dark gray 0x111111, the text's visibility would be very bad.

In addition, I want the text color to be black or white in order to not over-color the app.

So how can I determine, if white or black is the better color for the textcolor, based on a RGB code I get from the server?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dominik Reinert
  • 1,075
  • 3
  • 12
  • 26

1 Answers1

2

You just should calculate contrast ratio for user color with black and white, then choose the color with higher ratio.

Here is description for calculating relative color contrast from RGB.

Note that relative luminance of white is 1.0 and for black is 0.0, so (if you are considering only black and white) you can just check if relative luminance of user color is <0.5 then use white, and use black otherwise.

Community
  • 1
  • 1
xnor
  • 250
  • 4
  • 14