I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better readability.
Here's an example in Flash/Actionscript (with demo): http://web.archive.org/web/20100102024448/http://theflashblog.com/?p=173
Any thoughts?
Cheers, Andre
UPDATE
Thanks to everyone's suggestions, here's the working code:
- (void) updateColor:(UIColor *) newColor
{
const CGFloat *componentColors = CGColorGetComponents(newColor.CGColor);
CGFloat colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
if (colorBrightness < 0.5)
{
NSLog(@"my color is dark");
}
else
{
NSLog(@"my color is light");
}
}
Thanks once again :)
If you want to find the brightness of the color, here is some pseudo code:
If it is > 0.5 it is bright, and otherwise dark.
Using Erik Nedwidek's answer, I came up with that little snippet of code for easy inclusion.
For everything that's not grayish, the RGB inverse of a color is usually highly contrasted with it. The demo just inverts the color and desaturates it (converts it to a gray).
But generating a nice soothing combination of colors is quite complicated. Look at :
http://particletree.com/notebook/calculating-color-contrast-for-legible-text/
Swift3
My solution to this problem in a category (drawn from other answers here). Also works with grayscale colors, which at the time of writing none of the other answers do.