在PHP中计算两种颜色之间的平均颜色,使用索引号作为参考值
在 PHP 中,我试图计算不同十六进制颜色之间的平均颜色(以十六进制表示)。但是,我还需要能够提供 0.0 到 1.0 之间的索引号。
例如:
如果我
$color1 = "#ffffff"
$color2 = "#0066CC"
编写一个函数来获取平均颜色,并且我将提供 0.0 作为索引号,则该函数需要返回“#ffffff
”。如果我提供 1.0 作为索引号,该函数将需要返回“#0066CC
”。但是,如果我提供 0.2,该函数将需要返回两种颜色之间的平均颜色,但仍然更接近于 $color1
而不是 $color2
。如果我提供索引号 0.5,我将获得两种颜色的精确平均颜色。
我已经尝试完成这个任务好几天了,但我似乎无法弄清楚!因此,任何帮助将不胜感激!
In PHP, I am trying to calculate the average color (in hex) between to different hex colors. However, I also need to be able to supply an index number between 0.0 and 1.0.
So for example:
I have
$color1 = "#ffffff"
$color2 = "#0066CC"
If I would write a function to get the average color and I would supply 0.0 as the index number, the function would need to return "#ffffff
". If I would supply 1.0 as the index number, the function would need to return "#0066CC
". However if I would supply 0.2, the function would need to return an average color between the two colors, but still closer to $color1
than to $color2
. If I would supply index number 0.5, I would get the exact average color of both colors.
I have been trying to accomplish this for several days now but I can't seem to figure it out! Any help would therefor be greatly appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
为了讨论的目的,我们假设每种颜色都有一个“值”。然后,您想要做的事情就足够简单了:
因此,困难的部分是弄清楚每种颜色的“值”是什么。
您可以使用简单的 RGB 值,其中每种颜色的“值”是一组三个整数:
此处需要分别对每个数组元素进行乘法和加法。我认为现在应该很容易制作一个简单易用的函数来自己混合颜色。
如果这不是您所需要的,那么您可以使用 HSL 值或更适合您的应用程序的其他一些指标。这个想法将保持不变。
Let's assume that each color has a "value" for the purposes of this discussion. Then, what you want would be simple enough to do:
So, the hard part is figuring out what the "value" of each color is.
You could go with simple RGB values, where the "value" of each color is a set of three integers:
The multiplications and addition would need to be done on each array element separately here. I think at this point it should be easy to make a simple-to-use function to mix colors yourself.
If this is not what you need, then you can go with HSL values or some other metric that better suits your application. The idea would remain the same.
我不确定它是否会编译,但如果你想要背后的数学原理,它会是这样的:
为了简单起见,总是让
$color1
大于$color2
。I am not sure if it will compile but if you want the math behind this it would go something like this:
For simplicity, always have
$color1
be bigger than$color2
.您可以尝试:
查看
You can try:
See it
我尝试使用上面提到的功能:
I tried this using the functions mentioned above:
或者使用数组作为输入:
Or using an array as input :