[英]Convert [0,1] floating-point value to hex color
Is there a convenient way to convert a floating-point value in the range [0,1] to a HTML hex color using a specified gradient? 是否有一种方便的方法可以使用指定的渐变将[0,1]范围内的浮点值转换为HTML十六进制颜色?
At the moment, I am using: 目前,我正在使用:
.myclass {fill:red, fill-opacity:FLOATINGVAL}
But this is a somewhat restrictive gradient to work with. 但这是一个有点限制的梯度。
Consider something like: 考虑类似:
def blend(color, alpha, base=[255,255,255]):
'''
color should be a 3-element iterable, elements in [0,255]
alpha should be a float in [0,1]
base should be a 3-element iterable, elements in [0,255] (defaults to white)
'''
out = [int(round((alpha * color[i]) + ((1 - alpha) * base[i]))) for i in range(3)]
return out
print blend([255,0,0], 0) # [255, 255, 255] (White)
print blend([255,0,0], 0.25) # [255, 191, 191]
print blend([255,0,0], 0.5) # [255, 128, 128]
print blend([255,0,0], 0.75) # [255, 64, 64]
print blend([255,0,0], 1) # [255,0,0] (Red)
# Or RGB hex values instead of lists:
def to_hex(color):
return ''.join(["%02x" % e for e in color])
print to_hex(blend([255,0,0], 0)) # ffffff (White)
print to_hex(blend([255,0,0], 0.25)) # ffbfbf
print to_hex(blend([255,0,0], 0.5)) # ff8080
print to_hex(blend([255,0,0], 0.75)) # ff4040
print to_hex(blend([255,0,0], 1)) # ff0000 (Red)
In terms of how this function works with the gradients you listed [1], color
is the color at the right of the gradient bars while alpha
is your position on the gradient bar (0.0 far left, 1.0 far right) 就此功能如何处理您列出的渐变 [1]而言, color
是渐变条右侧的颜色,而alpha
是您在渐变条上的位置(最左侧为0.0,最右侧为1.0)
[1] This will only work with 2-color gradients -- your "color" and "white" (or whatever you specify base
as) (ie gradients from that image like Blues
, Greens
, Grays
, etc.) [1]这仅适用于2色渐变-您的“颜色”和“白色”(或您指定的base
)(例如,该图像的渐变,例如Blues
, Greens
, Grays
等)。
You won't be able to generate gradients like YlGnBu
with this function. 使用此功能将无法生成像YlGnBu
这样的渐变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.