首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将[0,1]浮点值转换为十六进制颜色

将[0,1]浮点值转换为十六进制颜色
EN

Stack Overflow用户
提问于 2015-03-07 04:54:59
回答 1查看 2.2K关注 0票数 0

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

目前,我正在使用:

代码语言:javascript
复制
.myclass {fill:red, fill-opacity:FLOATINGVAL}

但这是一个有点限制性的梯度。

EN

Stack Overflow用户

发布于 2015-03-07 05:14:12

考虑一下这样的情况:

代码语言:javascript
复制
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 listed1而言,color是渐变条右侧的颜色,而alpha是您在渐变条上的位置(最左侧为0.0,最右侧为1.0 )

1这只适用于两种颜色的渐变--你的“颜色”和“白色”(或者任何你指定的base )(即来自图像的渐变,如BluesGreensGrays等)。

你不能用这个函数来生成像YlGnBu这样的渐变。

票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28907480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档