Reputation: 3
I am looking to make a function that can output colors of a gradient. Let me explain more...
iterations = 5
startcolor = 0xa480ff
endcolor = 0x80bdff
colors = []
for x in range(1, iterations):
colors[x-1] = color
In the colors[x-1] = color
line, I would like to calculate the color that would be at the percentage of x
on a gradient. For example, if x
is 3
and iterations
is 5
, then color
would be halfway between a gradient of startcolor
and endcolor
. 1
would be startcolor
, and 5
would be endcolor
.
Upvotes: 0
Views: 280
Reputation: 541
Here is some code I made trying to do something similar. It good to note in my case I want a string.
As you can see I am lerping between each color value rgb(not a) individualy and adding them back together
I made this pretty quickly and haven't tested anything but the two functions.
def lerp(a, b, p):
return a + ((b - a) * p)
def lerpH(c1, c1, p):
r = lerp(int(c1[:2], 16), int(c2[:2], 16), p)
g = lerp(int(c1[2:4], 16), int(c2[2:4], 16), p)
b = lerp(int(c1[4:6], 16), int(c2[4:6] ,16), p)
t = lambda _x: str(hex(int(_x)))[2:]
return f'{t(r)}{t(g)}{t(b)}'
iterations = 5
startcolor = "a480ff"
# startcolor = str(hex(0xa480ff))[2:] # for hex()
endcolor = "80bdff"
# endcolor = str(hex(0x80bdff))[2:] # for hex()
colors = []
for x in range(0, iterations):
colors[x] = lerpH(startcolor, endcolor, float(x)/iterations)
#colors[x] = int(colors[x], 16) # this is to convert back to hex
Upvotes: -1
Reputation: 59445
If you think that a simple linear interpolation is sufficient as you stated in your comment, you may give this a try:
iterations = 5
startcolor = 0xa480ff
endcolor = 0x80bdff
colors = []
start_r, start_g, start_b = startcolor >> 16, startcolor >> 8 & 0xff, startcolor & 0xff
end_r, end_g, end_b = endcolor >> 16, endcolor >> 8 & 0xff, endcolor & 0xff
delta_r, delta_g, delta_b = (end_r - start_r) / iterations, (end_g - start_g) / iterations, (
end_b - start_b) / iterations
for x in range(iterations + 1):
r = int(start_r + delta_r * x)
g = int(start_g + delta_g * x)
b = int(start_b + delta_b * x)
colors.append(int(r << 16 | g << 8 | b))
print(*(f"{c:x}" for c in colors))
This should print:
a480ff 9c8cff 9598ff 8ea4ff 87b0ff 80bdff
Upvotes: 1