Skip to content

Instantly share code, notes, and snippets.

@JigarM
Last active August 29, 2015 14:03
Show Gist options
  • Save JigarM/829ba1adf4613aa78fc4 to your computer and use it in GitHub Desktop.
Save JigarM/829ba1adf4613aa78fc4 to your computer and use it in GitHub Desktop.
ColorConvert.js For Titanium
var hsv2rgb = function(hsv) {
var h = hsv.hue, s = hsv.sat, v = hsv.val;
var rgb, i, data = [];
if (s === 0) {
rgb = [v, v, v];
} else {
h = h / 60;
i = Math.floor(h);
data = [v * (1 - s), v * (1 - s * (h - i)), v * (1 - s * (1 - (h - i)))];
switch(i) {
case 0:
rgb = [v, data[2], data[0]];
break;
case 1:
rgb = [data[1], v, data[0]];
break;
case 2:
rgb = [data[0], v, data[2]];
break;
case 3:
rgb = [data[0], data[1], v];
break;
case 4:
rgb = [data[2], data[0], v];
break;
default:
rgb = [v, data[0], data[1]];
break;
}
}
return '#' + rgb.map(function(x) {
return ("0" + Math.round(x * 255).toString(16)).slice(-2);
}).join('');
};
/**
* HSV to RGB color conversion
*
* H runs from 0 to 360 degrees
* S and V run from 0 to 100
*
* Ported from the excellent java algorithm by Eugene Vishnevsky at:
* http://www.cs.rit.edu/~ncs/color/t_convert.html
*
* Refffered Concepr From http://snipplr.com/view/14590/hsv-to-rgb/
*/
function hsvToRgb(h, s, v) {
var r, g, b;
var i;
var f, p, q, t;
// Make sure our arguments stay in-range
h = Math.max(0, Math.min(360, h));
s = Math.max(0, Math.min(100, s));
v = Math.max(0, Math.min(100, v));
// We accept saturation and value arguments from 0 to 100 because that's
// how Photoshop represents those values. Internally, however, the
// saturation and value are calculated from a range of 0 to 1. We make
// That conversion here.
s /= 100;
v /= 100;
if (s == 0) {
// Achromatic (grey)
r = g = b = v;
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
h /= 60;
// sector 0 to 5
i = Math.floor(h);
f = h - i;
// factorial part of h
p = v * (1 - s);
q = v * (1 - s * f);
t = v * (1 - s * (1 - f));
switch(i) {
case 0:
r = v;
g = t;
b = p;
break;
case 1:
r = q;
g = v;
b = p;
break;
case 2:
r = p;
g = v;
b = t;
break;
case 3:
r = p;
g = q;
b = v;
break;
case 4:
r = t;
g = p;
b = v;
break;
default:
// case 5:
r = v;
g = p;
b = q;
}
return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment