Last active
May 19, 2021 06:22
-
-
Save kaishin/8934076 to your computer and use it in GitHub Desktop.
Get whether a color is dark or light using either luminance or lightness.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface UIColor (isLight) | |
- (CGFloat)lightness; | |
- (CGFloat)perceivedLightness; | |
- (CGFloat)perceivedLightnessW3C; | |
- (BOOL)isLight; | |
- (BOOL)isPerceivedLightW3C; | |
- (BOOL)isPerceivedLight; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "UIColor+isLight.h" | |
@implementation UIColor (isLight) | |
- (BOOL)isLight | |
{ | |
return [self lightness] >= .7; | |
} | |
- (CGFloat)lightness | |
{ | |
CGFloat hue, saturation, brightness, alpha; | |
[self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]; | |
CGFloat lightness = (2 - saturation) * brightness / 2; | |
return lightness; | |
} | |
- (BOOL)isPerceivedLight | |
{ | |
return [self perceivedLightness] >= .5; | |
} | |
- (CGFloat)perceivedLightness | |
{ | |
CGFloat red, green, blue, alpha; | |
[self getRed:&red green:&green blue:&blue alpha:&alpha]; | |
CGFloat lightness = 0.2126 * red + 0.7152 * green + 0.0722 * blue; | |
return lightness; | |
} | |
- (BOOL)isPerceivedLightW3C | |
{ | |
return [self perceivedLightnessW3C] >= .5; | |
} | |
- (CGFloat)perceivedLightnessW3C | |
{ | |
CGFloat red, green, blue, alpha; | |
[self getRed:&red green:&green blue:&blue alpha:&alpha]; | |
CGFloat lightness = 0.299 * red + 0.587 * green + 0.114 * blue; | |
return lightness; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment