Check if UIColor is dark or bright?

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

    Using Erik Nedwidek's answer, I came up with that little snippet of code for easy inclusion.

    - (UIColor *)readableForegroundColorForBackgroundColor:(UIColor*)backgroundColor {
        size_t count = CGColorGetNumberOfComponents(backgroundColor.CGColor);
        const CGFloat *componentColors = CGColorGetComponents(backgroundColor.CGColor);
    
        CGFloat darknessScore = 0;
        if (count == 2) {
            darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[0]*255) * 587) + ((componentColors[0]*255) * 114)) / 1000;
        } else if (count == 4) {
            darknessScore = (((componentColors[0]*255) * 299) + ((componentColors[1]*255) * 587) + ((componentColors[2]*255) * 114)) / 1000;
        }
    
        if (darknessScore >= 125) {
            return [UIColor blackColor];
        }
    
        return [UIColor whiteColor];
    }
    

提交回复
热议问题