【问题标题】:Convert [0,1] floating-point value to hex color将 [0,1] 浮点值转换为十六进制颜色
【发布时间】:2015-03-06 20:54:58
【问题描述】:

有没有一种方便的方法可以使用指定的渐变将 [0,1] 范围内的浮点值转换为 HTML 十六进制颜色?

目前,我正在使用:

.myclass {fill:red, fill-opacity:FLOATINGVAL}

但这是一个有点限制性的渐变。

【问题讨论】:

  • 你想用 Python 还是 CSS?
  • 您可以通过将 RGB 值与白色混合来生成由 CSS 技巧产生的颜色。见this related。在接受的答案中,alpha 是您的 FLOATINGVALnew 是红色的 RGB([255,0,0]),old 是白色的 RGB([255,255,255])。
  • 我想起了 Matplotlib 渐变(参见 here)。我不一定需要在 CSS 中做所有事情:我只需要能够在通过某种包生成的某种渐变上指定一种颜色。

标签: python html colors


【解决方案1】:

考虑类似:

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)

关于此函数如何与gradients you listed[1] 一起使用,color 是渐变条右侧的颜色,而alpha 是您在渐变条上的位置(0.0 最左侧,1.0 远对)

[1] 这仅适用于 2 色渐变 - 您的“颜色”和“白色”(或任何您指定的 base)(即来自该图像的渐变,如 BluesGreensGrays等)

您将无法使用此函数生成像YlGnBu 这样的渐变。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-17
    • 2014-03-01
    • 1970-01-01
    • 2016-11-20
    • 2019-10-29
    • 2011-03-05
    • 2020-08-06
    • 2016-06-02
    相关资源
    最近更新 更多