How to check if hex color is “too black”?

前端 未结 8 1632
谎友^
谎友^ 2020-12-04 05:21

I\'m trying to evaluate the darkness of a color chosen by a color picker to see if it\'s \"too black\", and if so, set it to white. I thought I could use the first character

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-04 05:33

    I realize this conversation is a few years old, but it is still relevant. I wanted to add that my team was having the same issue in Java (SWT) and found this to be a bit more accurate:

    private Color getFontColor(RGB bgColor) {
        Color COLOR_BLACK = new Color(Display.getDefault(), 0, 0, 0);
        Color COLOR_WHITE = new Color(Display.getDefault(), 255, 255, 255);
    
        double luminance = Math.sqrt(0.241 
           * Math.pow(bgColor.red, 2) + 0.691 * Math.pow(bgColor.green, 2) +  0.068 
           * Math.pow(bgColor.blue, 2));
        if (luminance >= 130) {
            return COLOR_BLACK;
        } else {
            return COLOR_WHITE;
        }
    }
    

提交回复
热议问题