views:

19

answers:

2

Hi there

I want to show some images like this examplealt text

The fill color is decided by a field in the data base with the color in hex (ex:ClassX -> Color: #66FFFF). Now, I want to show data above a fill with the selected color (like in the image above) but i need to know if the color is dark or light so i know if the words should be in white or black. Is there a way? tks

A: 

I've never done anything like this, but what about writing a function to check the values of each of the colors against the median color of Hex 7F (FF / 2). If two of the three colors are greater than 7F, then you're working with a darker color.

DJ Quimby
+1  A: 

Building on my answer to a similar question.

You need to break the hex code into 3 pieces to get the individual red, green, and blue intensities. Each 2 digits of the code represent a value in hexadecimal (base-16) notation. I won't get into the details of the conversion here, they're easy to look up.

Once you have the intensities for the individual colors, you can determine the overall intensity of the color and choose the corresponding text.

if (red*0.299 + green*0.587 + blue*0.114) > 186 use #000000 else use #ffffff
Mark Ransom
Way better answer than mine
DJ Quimby
Tks Mark. Tryed a few changes: calculated red green and blue by the first digit only (less precise but is the digit with more weight) and instead of 186 used 9. works a little bit better for me, specially with greens.
DJPB
@DJPB, that sounds like a great simplification. The conversion from RGB to gray almost certainly introduces more errors than dropping the second digit, and all you need is an approximation anyway. The choice of threshold has a lot of leeway too, human perception is hard to pin down.
Mark Ransom