Last active

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

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/

View NSColor+isLight.h
1 2 3 4 5 6 7
#import <Cocoa/Cocoa.h>
 
@interface NSColor (isLight)
 
- (BOOL)isLight;
 
@end
View NSColor+isLight.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#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
View NSColor+isLight.h
1 2 3 4 5 6 7 8 9 10 11
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
}
}
View NSColor+isLight.h
1 2 3 4 5 6 7
#import <UIKit/UIKit.h>
 
@interface UIColor (isLight)
 
- (BOOL)isLight;
 
@end
View NSColor+isLight.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#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
View NSColor+isLight.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
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
}
}
View NSColor+isLight.h
1 2 3 4 5 6 7 8 9
@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;
}

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.