RGB2HSV conversion using actionscript…

rgb2hsv conversion

Another simple conversion function. This time it converts RGB values to HSV (Hue, Sat, Val).

function rgb2hsv(r,g,b)
{    
 var x, val, d1, d2, hue, sat, val;    
 r/=255;    
 g/=255;    
 b/=255;    
 x = Math.min(Math.min(r, g), b);    
 val = Math.max(Math.max(r, g), b);    
 if (x==val)
 {        
  return(”h is undefined, s: “+0+”,v: “+ val*100); //err obj
 }    
 d1 = (r == x) ? g-b : ((g == x) ? b-r : r-g);    
 d2 = (r == x) ? 3 : ((g == x) ? 5 : 1);    
 hue = Math.floor((d2-d1/(val-x))*60)%360;    
 sat = Math.floor(((val-x)/val)*100);    
 val = Math.floor(val*100);    
 return(hue+”,”+sat+”,”+val);
};

Have fun,

FLAIM

Replacing text inside strings

string replacer 

A small function that replaces parts of text with different text. Useful for HTML text and XML. Example usage - replacing special characters of a users choice from a XML file to html tags for use with htmlText.

Here it is (works both in AS2 and AS3):

var test:String = “A big bad wolf ate a big sheep.”;
var some_result:String;
function replacer(ss,searchStr, replaceStr)
{
    var arr:Array = ss.split(searchStr);
    return arr.join(replaceStr);
};
replacer(test,”big”,”small”);
trace(replacer(test,”big”,”small”)); // returns “A small bad wolf ate a small sheep.”

FLAIM

switching places within an Array() using XOR

switching places 

This small function switches places of two array elements. Very useful and quick. I’ve needed to write this for a simple aplication that uses layers (like the photoshop ones) and changes the places of elements in the layer when the user moves the layer to a different depth :)

 Here it is:

var my_array:Array = new Array(12,3,55,24);
function swap_indexes(a,b)
{
 my_array[a] ^= my_array[b];
 my_array[b] ^= my_array[a];
 my_array[a] ^= my_array[b];
 trace(my_array); // 55,3,12,24
};
swap_indexes(0,2); // these are the two array indexes you want to switch place

The above works both in AS2 and AS3 - Hope it helps someone :)

Of course the above method works only with Numbers. If you want to use it with different variable types like String you should use the old and slow method.

It would look like this (works both AS2 and AS3):

var my_array:Array = new Array(”mike”,”dan”,”jeremy”,”chris”);
var t:String;
function swap_indexes(a,b)
{
 t=my_array[a];
 my_array[a] = my_array[b];
 my_array[b] = t;
 trace(my_array); // “jeremy”,”dan”,”mike”,”chris”
};
swap_indexes(0,2); // these are the two array indexes you want to switch place

FLAIM