【问题标题】:Get Inverse value for hexadecimal background color - PHP获取十六进制背景颜色的逆值 - PHP
【发布时间】:2019-07-20 00:15:53
【问题描述】:

我的页面中有一个日历,其中给定颜色作为事件背景颜色(深蓝色或栗色)。背景颜色应用得很好。 (如图所示)

现在我申请前景 |易于阅读的文本颜色。 (可以与我的“黑色”=>“白色”或“深棕色”=>“白色”完全相反)。

这是我到目前为止所做的事情

public static function GenerateInverseColor($color){


        $color       = trim($color);
        $prependHash = FALSE;

        if(strpos($color,'#')!==FALSE) {
            $prependHash = TRUE;
            $color       = str_replace('#',NULL,$color);
        }

        switch($len=strlen($color)) {
            case 3:
                $color=preg_replace("/(.)(.)(.)/","\\1\\1\\2\\2\\3\\3",$color);
                break;
            case 6:
                break;
            default:
                trigger_error("Invalid hex length ($len). Must be a minimum length of (3) or maxium of (6) characters", E_USER_ERROR);
        }

        if(!preg_match('/^[a-f0-9]{6}$/i',$color)) {
            $color = htmlentities($color);
            trigger_error( "Invalid hex string #$color", E_USER_ERROR );
        }

        $r = dechex(255-hexdec(substr($color,0,2)));
        $r = (strlen($r)>1)?$r:'0'.$r;
        $g = dechex(255-hexdec(substr($color,2,2)));
        $g = (strlen($g)>1)?$g:'0'.$g;
        $b = dechex(255-hexdec(substr($color,4,2)));
        $b = (strlen($b)>1)?$b:'0'.$b;

        return ($prependHash?'#':NULL).$r.$g.$b;
}

我也试过了

// provide balck|white color for any color
public static function GenerateInverseColor($hexcolor){

        $hexcolor       = trim($hexcolor);

        $r = hexdec(substr($hexcolor,0,2));
        $g = hexdec(substr($hexcolor,2,2));
        $b = hexdec(substr($hexcolor,4,2));
        $yiq = (($r*299)+($g*587)+($b*114))/1000;
        return ($yiq >= 128) ? 'black' : 'white';

}

还有

public static function GenerateInverseColor($hexcolor){
 if (strlen($color) != 6){ return '000000'; }
    $rgb = '';
    for ($x=0;$x<3;$x++){
        $c = 255 - hexdec(substr($color,(2*$x),2));
        $c = ($c < 0) ? 0 : dechex($c);
        $rgb .= (strlen($c) < 2) ? '0'.$c : $c;
    }
    return '#'.$rgb;
}

这些方法都不能帮助提供所需的输出。

我已经尝试了几乎所有我能找到的答案,但没有一个有帮助。图像中的颜色组合也是基于 SO 的一些答案,但无法满足我的要求

【问题讨论】:

标签: php colors hex


【解决方案1】:

我过去曾使用ColorJizz 库在 PHP 中处理颜色。它应该有计算文本/背景东西的方法,我记得用它来完成这样的任务。

请注意,完全不能保证纯粹从数学上使用随机颜色会产生良好的 UI。颜色感知比它的成分更复杂。更不用说你可以得到对比鲜明的颜色,但在美学上看起来像垃圾。

【讨论】:

  • 抱歉,我不能随意使用库来完成这项任务
猜你喜欢
  • 2014-03-03
  • 2018-06-06
  • 2012-09-21
  • 2019-03-26
  • 2017-06-25
  • 2016-04-02
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
相关资源
最近更新 更多