Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Programmatically determine the perceived lightness of a color. More details on: http://robots.thoughtbot.com/closer-look-color-lightness + Online tool: http://thoughtbot.github.io/color-lightness-test/
@function color-is-light($hex-color) {
$red: red(rgba($hex-color, 1.0));
$green: green(rgba($hex-color, 1.0));
$blue: blue(rgba($hex-color, 1.0));
$lightness: ($red * 0.2126 + $green * 0.7152 + $blue * 0.0722) / 255;
@return $lightness > .6;
}
#import <Cocoa/Cocoa.h>
@interface NSColor (isLight)
- (BOOL)isLight;
@end
#import "NSColor+isLight.h"
@implementation NSColor (isLight)
- (CGFloat)luma
{
CGFloat luma = 0.2126 * self.redComponent + 0.7152 * self.greenComponent + 0.0722 * self.blueComponent;
return luma;
}
- (BOOL)isLight
{
return self.luma >= .6;
}
@end
import Cocoa
extension NSColor {
var luma: Float {
return 0.2126 * Float(redComponent) + 0.7152 * Float(greenComponent) + 0.0722 * Float(blueComponent)
}
var isLight: Bool {
return luma >= 0.6
}
}
#import <UIKit/UIKit.h>
@interface UIColor (isLight)
- (BOOL)isLight;
@end
#import "UIColor+isLight.h"
@implementation UIColor (isLight)
- (CGFloat)luma
{
CGFloat luma;
CGFloat red;
CGFloat blue;
CGFloat green;
CGFloat alpha;
[self getRed:&red green:&green blue:&blue alpha:&alpha];
luma = 0.2126 * red + 0.7152 * green + 0.0722 * blue;
return luma;
}
- (BOOL)isLight
{
return self.luma >= .6;
}
@end
import UIKit
extension UIColor {
var redComponent: CGFloat {
var red: CGFloat = 0
self.getRed(&red, green:nil, blue:nil, alpha:nil)
return red
}
var greenComponent: CGFloat {
var green: CGFloat = 0
self.getRed(nil, green:&green, blue:nil, alpha:nil)
return green
}
var blueComponent: CGFloat {
var blue: CGFloat = 0
self.getRed(nil, green: nil, blue: &blue, alpha: nil)
return blue
}
var luma: Float {
return 0.2126 * Float(redComponent) + 0.7152 * Float(greenComponent) + 0.0722 * Float(blueComponent)
}
var isLight: Bool {
return luma >= 0.6
}
}
@edwardloveall

This comment has been minimized.

Copy link

edwardloveall commented Apr 3, 2014

These are great! You might consider using less common variables in the SASS version. I ran into an issue where I had $red defined and it caused conflicts. Maybe something like $_red, $_green, $_blue, and $_lightness

@timonweber

This comment has been minimized.

Copy link

timonweber commented Sep 10, 2019

Thank you for the insights, I really enjoyed reading your article!

But can you explain why you used > 0.6 instead of > 0.5 for calling a color light?

@kaishin

This comment has been minimized.

Copy link
Owner Author

kaishin commented Sep 25, 2019

@timonweber That’s up to your specific implementation, but 0.6 is on the safer side, since it’s closer to how human sight perceives color.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.