views:

61

answers:

5
+1  Q: 

UIColor comparison

Given a UIColor, I need to determine if it is "light" or "dark". If I could access the hex value of the color, I could just check if it was greater than or less than a certain threshold hex number, but there appears to be no way to do that. Is there? Or is there another way I could check the brightness value of a UIColor?

A: 

UIColor (and CGColorRef) are generally described in RGB values. If you want to determine light or dark, you'll probably want to convert these values to something like Hue/Saturation/Brightness. But there are no built in functions like you are looking for.

Jerry Jones
+2  A: 

[UIColor CGColor] will get you a CGColorRef, from there you can do CGColorGetComponents to get the individual components. Getting the "brightness" value depends on your definition of brightness. Getting an average of the components (in case of RGB color space) might be a good start.

unbeli
I wouldn't use the average, the human eye is peak responsive. Use the brightest of the RGB components to gauge brightness. 00FF00 will seem brighter than 555555 but they have the same average.
progrmr
This wont work very well — an example: the colors rgb(108 11 11) and rgb(107 91 12) actually have the same brightness (0.42) but the sums (and so the averages) are 130 and 210. not really close.
vikingosegundo
as I said, it depends very much on how you define "brightness". Human eye is not the only possible measurement device.
unbeli
A: 

here is a guide (with code provided) on UIColor expansion (using a category) and has methods such as get hexStringFromColor: It should be what you're looking for. UIColor expansion Note: I did not write this blog or code.

Jesse Naugher
This is good. hexStringFromColor gives me the hex string in the format "01f3df". But I can't figure out how to convert that to an actual hex number for comparison.
sol
the r g b values wont help, as this model says nothing about brightness of a color. You can tell it for each of its components, but not for all of them together.
vikingosegundo
+1  A: 

You could install this Category for extending UIColor for knowing HSV/HSB and compare [aUIColor brightness]

vikingosegundo
That's how I do it, if the value (V in HSV, aka brightness) is < 0.5 then it's dark.
progrmr
Thanks, this is perfect. I can just check if greater than or less than .5, like progmr suggests.
sol
A: 

Proposed algorithm to calculate color / color brightness difference: http://maestric.com/doc/color_brightness_difference_calculator (based on w3c paper)

Shazron