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] This will only work with 2-color gradients -- your "color" and "white" (or whatever you specify base
as) (i.e. gradients from that image like Blues
, Greens
, Grays
, etc.)
You won't be able to generate gradients like YlGnBu
with this function.