Skip to content

Instantly share code, notes, and snippets.

@jessearmand
Forked from kaishin/NSColor+isLight.h
Created May 16, 2018 03:11
Show Gist options
  • Save jessearmand/2a8c062949a39c656e8ad2f4c6f15e38 to your computer and use it in GitHub Desktop.
Save jessearmand/2a8c062949a39c656e8ad2f4c6f15e38 to your computer and use it in GitHub Desktop.
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment