I've been doing a LOT of work with color handling in my script as I'm using image.GetColorScheme() to pull the colors to generate a dynamic theme. It works great, and I can't wait to show it to everyone, but I figured I ought to share some of the helper code I wrote as I'm sure it'd be useful to more than just me.
This code makes extensive use out of the getRed, getGreen, getBlue, rgb, rgba helper functions and I won't bother repeating them unless somebody can't find them in helpers.txt. Also, I renamed RGB and RGBA to lowercase versions.
prettyPrint a color. Useful for logging:
function colToRgb(c, showPrefix) {
if (typeof showPrefix === 'undefined') showPrefix = true;
var alpha = getAlpha(c);
var prefix = '';
if (alpha < 255) {
if (showPrefix) prefix = 'rgba'
return prefix + '('+ getRed(c) + ', ' + getGreen(c) + ', ' + getBlue(c) + ', ' + alpha + ')';
} else {
if (showPrefix) prefix = 'rgb'
return prefix + '(' + getRed(c) + ', ' + getGreen(c) + ', ' + getBlue(c) + ')';
}
}
Calculate Brightness of a color:
function calcBrightness(c) {
var r = getRed(c);
var g = getGreen(c);
var b = getBlue(c);
return Math.round(Math.sqrt( 0.299*r*r + 0.587*g*g + 0.114*b*b ));
}
Create Shades (darker) or Tints (lighter) of a color. These two functions take a percent number, i.e. pass 20 instead of .2. Passing 100 to shade will result in solid black, 100 to tint is solid white.
color = rgb(81, 89, 72); // gray-ish green
darker = shadeColor(color, 30); // darker = rgb(57, 62, 50)
lighter = tintColor(color, 20); // lighter = rgb(116, 122, 109)
function shadeColor(color, percent) {
var red = getRed(color);
var green = getGreen(color);
var blue = getBlue(color);
return rgba(darkenColorVal(red, percent), darkenColorVal(green, percent), darkenColorVal(blue, percent), getAlpha(color));
}
function tintColor(color, percent) {
var red = getRed(color);
var green = getGreen(color);
var blue = getBlue(color);
return rgba(lightenColorVal(red, percent), lightenColorVal(green, percent), lightenColorVal(blue, percent), getAlpha(color));
}
// helpers, don't call directly
function darkenColorVal(color, percent) {
var shift = Math.max(color * percent / 100, percent / 2);
val = Math.round(color - shift);
return Math.max(val, 0);
}
function lightenColorVal(color, percent) {
val = Math.round(color + ((255-color) * (percent / 100)));
return Math.min(val, 255);
}