Reputation: 27
Does anyone know how to cycle through RGB values in python? Ex. R = 255, G = 255, B = 255
R -= 1 until 0 and then go back up and then make G go down and so on?
(This is for text colour in pygame)
Upvotes: 2
Views: 2311
Reputation: 231
You can use max()
to get the largest number within the tuple and subtract each number until all are equal to or less than zero, like this:
RGB = (255,200,201)
red = RGB[0]
green = RGB[1]
blue = RGB[2]
step = -1
for i in range( max(RGB) * 2 + 2):
print(
"R:",red if red > 0 else 0,
"G:",green if green > 0 else 0,
"B:",blue if blue > 0 else 0
)
if all( map( lambda x: True if x < 0 else False, [red,green,blue] ) ):
step = 1
red += step
green += step
blue += step
As you can see, after all numbers are equal to or less than zero, the variable "step" is set to 1. This way we can make the numbers go back to their original values by summing them.
Upvotes: 2
Reputation: 14906
It's a fairly easy shift to do - add some amount to each component of the colour, then ensure it is still within the legal bounds of the colour-value. Here I've assumed 8-bit colour, so the valid range is 0-255. Obviously if the code needed say 16 bit colour, the range would be bigger.
def shiftColour( colour, level_shift=-1 ):
""" Return the colour with each component shifted (with boundary looping)"""
red, green, blue = colour
red += level_shift # handle cycling in +/- for any level_shift
if ( red < 0 ):
red = 255
elif ( red > 255 ):
red = 0
green += level_shift
if ( green < 0 ):
green = 255
elif ( green > 255 ):
green = 0
blue += level_shift
if ( blue < 0 ):
blue = 255
elif ( blue > 255 ):
blue = 0
return ( red, green, blue ) # re-combine, back into a colour
Shifting back down from the high-point is just a matter of remembering where the cycle is at. You probably don't want to use the last say 50 values, since the colour would be mostly black.
### Main
colour = ( 255, 245, 235 )
delta = 1
for i in range( 300 ):
colour = shiftColour( colour, delta )
print("R=%d, G=%d, B=%d" % ( colour[0], colour[1], colour[2] ) )
if ( i % 50 == 0 ):
delta *= -1
print( "direction-change" )
Upvotes: 2
Reputation: 827
Something like this?
r = 255
g = 255
b = 255
while(r>0):
r-=1
print("Red: %s" %r)
if(r==0):
while(g>0):
g-=1
print("Green: %s" %g)
if(g==0):
while(b>0):
b-=1
print("Blue: %s" %b)
I'm sure you can modify this abit to make it have a looping fade effect if that's what you're looking for.
Upvotes: 1