Check if UIColor is dark or bright?

前端 未结 14 2074
醉酒成梦
醉酒成梦 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:44

    My solution to this problem in a category (drawn from other answers here). Also works with grayscale colors, which at the time of writing none of the other answers do.

    @interface UIColor (Ext)
    
        - (BOOL) colorIsLight;
    
    @end
    
    @implementation UIColor (Ext)
    
        - (BOOL) colorIsLight {
            CGFloat colorBrightness = 0;
    
            CGColorSpaceRef colorSpace = CGColorGetColorSpace(self.CGColor);
            CGColorSpaceModel colorSpaceModel = CGColorSpaceGetModel(colorSpace);
    
            if(colorSpaceModel == kCGColorSpaceModelRGB){
                const CGFloat *componentColors = CGColorGetComponents(self.CGColor);
    
                colorBrightness = ((componentColors[0] * 299) + (componentColors[1] * 587) + (componentColors[2] * 114)) / 1000;
            } else {
                [self getWhite:&colorBrightness alpha:0];
            }
    
            return (colorBrightness >= .5f);
        }
    
    @end
    

提交回复
热议问题