Reputation: 410
So I'm trying to make a color gradient, from a color to completely black, as well as from a color to completely white.
So say I have (175, 250, 255)
and I want to darken that color exactly 10 times to end at (0, 0, 0)
, how could I do this?
I'd also like to brighten the color, so I'd like to brighten it exactly 10 times and end at (255, 255, 255)
.
Upvotes: 2
Views: 11513
Reputation: 10819
Something like this maybe:
def interpolate(color_a, color_b, t):
# 'color_a' and 'color_b' are RGB tuples
# 't' is a value between 0.0 and 1.0
# this is a naive interpolation
return tuple(int(a + (b - a) * t) for a, b in zip(color_a, color_b))
def main():
color_a = (175, 250, 255)
color_b = (0, 0, 0)
number_of_steps = 10
colors = [interpolate(color_a, color_b, t/number_of_steps) for t in range(number_of_steps+1)]
for color in colors:
print(color)
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Output:
(175, 250, 255)
(157, 225, 229)
(140, 200, 204)
(122, 175, 178)
(105, 150, 153)
(87, 125, 127)
(70, 100, 102)
(52, 75, 76)
(35, 50, 51)
(17, 25, 25)
(0, 0, 0)
Upvotes: 5
Reputation: 611
Could you reduce each value by 10% ten times? For example your colours would be:
175 250 255
157 225 229
140 200 204
122 175 178
105 150 153
87 125 127
70 100 102
52 75 76
35 50 51
17 25 25
0 0 0
Upvotes: 0
Reputation: 1008
Many ways to solve this one. One idea would be to find the difference between your current value to the target value and divide that by 10.
So (175, 250, 255)
to (0, 0, 0)
difference is (175, 250, 255)
, then divide that by ten to have what you would subtract each of the ten steps. So subtract (-17.5, -25, -25.5)
every step, rounding when needed.
Upvotes: 0
Reputation: 546
Perhaps the accepted answer to the same question by user Peter O. here will help: Given an RGB value, how do I create a tint (or shade)?.
Among several options for shading and tinting:
For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.
For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).
Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)
See also Violet Giraffe's comment about "gamma correction".
Upvotes: 2