如何用PHP生成更浅/更深的颜色? [英] How to generate lighter/darker color with PHP?

查看:321
本文介绍了如何用PHP生成更浅/更深的颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些颜色的十六进制值,例如#202010

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

如何在PHP中以百分比形式生成一个更亮或更暗的新颜色(例如20%更暗)

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

推荐答案

按照Frxstrem给出的示例调整颜色百分比是不理想的。

Adjusting colour by percent, as in the example given by Frxstrem, is not ideal.

如果颜色为黑色(RGB中为0,0,0),则将乘以零,这将不会产生任何变化。如果你的颜色是深灰色(例如RGB的2,2,2),你将需要减轻50%,只是移动到(3,3,3)。另一方面,如果你有一个RGB颜色(100,100,100),50%的调整将把你移动到(150,150,150),这是一个更大的变化比较。

If your colour is black (0,0,0 in RGB), you will be multiplying by zero, which will not yield any change at all. If your colour is dark gray (for instance 2,2,2 in RGB), you will have to lighten by 50% to just move up to (3,3,3). On the other hand, if you have an RGB colour of (100,100,100), the adjustment of 50% will move you up to (150,150,150), which is a much bigger change in comparison.

一个更好的解决方案是通过step / number(0-255)而不是百分比来调整,例如像这样(PHP代码):

A much better solution would be to adjust by step/number (0-255) instead of by percent, for instance like this (PHP code):

编辑2014-01-06:清理一下代码。

Edit 2014-01-06: Cleaned up the code a bit.

function adjustBrightness($hex, $steps) {
    // Steps should be between -255 and 255. Negative = darker, positive = lighter
    $steps = max(-255, min(255, $steps));

    // Normalize into a six character long hex string
    $hex = str_replace('#', '', $hex);
    if (strlen($hex) == 3) {
        $hex = str_repeat(substr($hex,0,1), 2).str_repeat(substr($hex,1,1), 2).str_repeat(substr($hex,2,1), 2);
    }

    // Split into three parts: R, G and B
    $color_parts = str_split($hex, 2);
    $return = '#';

    foreach ($color_parts as $color) {
        $color   = hexdec($color); // Convert to decimal
        $color   = max(0,min(255,$color + $steps)); // Adjust color
        $return .= str_pad(dechex($color), 2, '0', STR_PAD_LEFT); // Make two char hex code
    }

    return $return;
}

这篇关于如何用PHP生成更浅/更深的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆