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 prefer the block version:
Here is a Swift (3) extension to perform this check.
This extension works with greyscale colors. However, if you are creating all your colors with the RGB initializer and not using the built in colors such as
UIColor.black
andUIColor.white
, then possibly you can remove the additional checks.Tests:
Note: Updated to Swift 3 12/7/18
Swift 4 Version
For me using only CGColorGetComponents didn't worked, I get 2 components for UIColors like white. So I have to check the color spaceModel first. This is what I came up with that ended up being the swift version of @mattsven's answer.
Color space taken from here: https://stackoverflow.com/a/16981916/4905076
Simpler Swift 3 extension:
UIColor has the following method to convert to HSB color space: