How to generate lighter/darker color with PHP?

前端 未结 7 1310
北恋
北恋 2020-12-12 12:31

I have a hex value of some color, for example #202010.

How to generate a new color which is either lighter or darker given in percent (ie. 20% dar

7条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 13:17

    Torkil Johnsen's answer is based on fixed step which doesn't manipulate only brightness but also slightly changes the hue. Frxstrem's method has flaws too as Torkil Johnsen noted.

    I've taken this approach from a Github comment and improved the code. It works perfectly for any case.

    /**
     * Increases or decreases the brightness of a color by a percentage of the current brightness.
     *
     * @param   string  $hexCode        Supported formats: `#FFF`, `#FFFFFF`, `FFF`, `FFFFFF`
     * @param   float   $adjustPercent  A number between -1 and 1. E.g. 0.3 = 30% lighter; -0.4 = 40% darker.
     *
     * @return  string
     */
    function adjustBrightness($hexCode, $adjustPercent) {
        $hexCode = ltrim($hexCode, '#');
    
        if (strlen($hexCode) == 3) {
            $hexCode = $hexCode[0] . $hexCode[0] . $hexCode[1] . $hexCode[1] . $hexCode[2] . $hexCode[2];
        }
    
        $hexCode = array_map('hexdec', str_split($hexCode, 2));
    
        foreach ($hexCode as & $color) {
            $adjustableLimit = $adjustPercent < 0 ? $color : 255 - $color;
            $adjustAmount = ceil($adjustableLimit * $adjustPercent);
    
            $color = str_pad(dechex($color + $adjustAmount), 2, '0', STR_PAD_LEFT);
        }
    
        return '#' . implode($hexCode);
    }
    

    Here is an example result:

提交回复
热议问题