How to generate lighter/darker color with PHP?

前端 未结 7 1171
北恋
北恋 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:22

    If you want a simple implementation and you don't care that much about the values being specifically above 50% lightness (or whatever your threshold), you can use my solution for lighter colors:

    $color = sprintf('#%06X', mt_rand(0xFFFFFF / 1.5, 0xFFFFFF));
    

    The idea is to generate a random color in the higher part of the palette. You can adjust the results to be more or less dark by changing the "1.5" value:

    • larger will expand the palette into darker colors
    • smaller will curb it to lighter colors

    You can do the same for darker colors by setting the starting point of the random function to "0x000000" and dividing the end limit:

    $color = sprintf('#%06X', mt_rand(0x000000, 0xFFFFFF / 1.5));
    

    I know this is not a precise but it works for me.

提交回复
热议问题