In my ongoing question for a programmatically controlled gradient function (here and here) I stumbled upon a built in python library that does conversions between RGB and HSV. This allows be manipulate the RGB colors in the manner I desire. So I wrote a function to do so. However not being the most skilled in python, I have no idea if it can be done in a better manner.
This function:
- Takes an RGB value in the form of #FFAABB etc
- Converts it to HSV
- Multiples the V component by a user supplied value
- Converts it back to RGB
- Reformats it back to #AABBCC format etc
Note that rgb_to_hsv returns a tuple, which of course is immutable in python.
def mulColorV(self, rgbHex, factV):
"""
Custom method that can be invoked directly on this component.
Arguments:
self: A reference to the component that is invoking this function.
rgbHex:
factV:
"""
try:
import colorsys
rgbDec=list(int(rgbHex[i:i+2], 16)/255.0 for i in (1, 3, 5))
hsvDec=list(colorsys.rgb_to_hsv(rgbDec[0],rgbDec[1],rgbDec[2]))
hsvDec[2]*=factV
if hsvDec[2]>1.0:
hsvDec[2]=1.0
if hsvDec[2]<0.0:
hsvDec[2]=0.0
newRgb=colorsys.hsv_to_rgb(hsvDec[0],hsvDec[1],hsvDec[2])
newHex='#{0:02X}{1:02X}{2:02X}'.format(int(newRgb[0]*255),int(newRgb[1]*255),int(newRgb[2]*255))
return newHex
except:
return '#000000'