Check if UIColor is dark or bright?

前端 未结 14 1967
醉酒成梦
醉酒成梦 2020-11-29 17:20

I need to determine whether a selected UIColor (picked by the user) is dark or bright, so I can change the color of a line of text that sits on top of that color, for better

相关标签:
14条回答
  • 2020-11-29 17:47

    If you prefer the block version:

    BOOL (^isDark)(UIColor *) = ^(UIColor *color){
        const CGFloat *component = CGColorGetComponents(color.CGColor);
        CGFloat brightness = ((component[0] * 299) + (component[1] * 587) + (component[2] * 114)) / 1000;
    
        if (brightness < 0.75)
            return  YES;
        return NO;
    };
    
    0 讨论(0)
  • 2020-11-29 17:49
    - (BOOL)isColorLight:(UIColor*)color
    {
        CGFloat white = 0;
        [color getWhite:&white alpha:nil];
        return (white >= .85);
    }
    

    Added Swift 5 version:

    var white: CGFloat = 0.0
    color.getWhite(&white, alpha: nil)
    return white >= .85 // Don't use white background
    
    0 讨论(0)
提交回复
热议问题