iOS UIColor 深浅色判断

以下常见的 Color 判断是没有问题的,虽说有那么点误差

- (BOOL)isLighterColor:(UIColor *)color {
    const CGFloat* components = CGColorGetComponents(color.CGColor);
    return (components[0]+components[1]+components[2])/3 >= 0.5;
}

通过把 RGB 模式转换成YUV 模式,而 Y 是明亮度(灰阶)

- (BOOL)isLighterColorWithRed:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue {
    BOOL isLighter = NO;
    if(red*0.299 + green*0.578 + blue*0.114 >= 192){
        //浅色
        isLighter = YES;
    }
    return isLighter;
}
- (BOOL)isLighterColorWithHXB:(NSInteger)hexColor {
    float red = ((float)((hexColor & 0xFF0000) >> 16))/255.0;
    float green = ((float)((hexColor & 0xFF00) >> 8))/255.0;
    float blue = ((float)(hexColor & 0xFF))/255.0;
    return [self isLighterColorWithRed:red green:green blue:blue];
}
相对来说还是 RGB 误差小一点的,选择其。

PS : lighterColor & darkerColor

- (UIColor *)lighterColor {
    if ([self isEqual:[UIColor whiteColor]]) {
        return [UIColor colorWithWhite:0.99 alpha:1.0];
    }
    if ([self isEqual:[UIColor blackColor]]) {
       return [UIColor colorWithWhite:0.01 alpha:1.0];
    }
    CGFloat hue, saturation, brightness, alpha, white;
    if ([self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]) {
        return [UIColor colorWithHue:hue
                          saturation:saturation
                          brightness:MIN(brightness * 1.3, 1.0)
                               alpha:alpha];
    } else if ([self getWhite:&white alpha:&alpha]) {
        return [UIColor colorWithWhite:MIN(white * 1.3, 1.0) alpha:alpha];
    }
    return nil;
}

- (UIColor *)darkerColor {
    if ([self isEqual:[UIColor whiteColor]]) {
        return [UIColor colorWithWhite:0.99 alpha:1.0];
    }
    if ([self isEqual:[UIColor blackColor]]) {
        return [UIColor colorWithWhite:0.01 alpha:1.0];
    }
    CGFloat hue, saturation, brightness, alpha, white;
    if ([self getHue:&hue saturation:&saturation brightness:&brightness alpha:&alpha]) {
        return [UIColor colorWithHue:hue
                          saturation:saturation
                          brightness:brightness * 0.75
                               alpha:alpha];
    } else if ([self getWhite:&white alpha:&alpha]) {
        return [UIColor colorWithWhite:MAX(white * 0.75, 0.0) alpha:alpha];
    }
    return nil;
}

你可能感兴趣的:(iOS UIColor 深浅色判断)