'Calculate a point between 2 colors
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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Selcuk |
