Sunday 23 August 2009

Extra colour functions

A range of extra functions are available to provide information about colours.
red(), green() and blue() provide access to the individual components of a colour.

These functions return float values, which makes them quite slow in practice.

This code snippet shows a method of brightening a colour by accessing the components:


// brightenColour
// an example showing basic colour manipulation
// using red(), green() and blue()

void setup()
{
size(400, 400);
smooth();
noStroke();
}

void draw()
{
int h=100;
int y=0;
color c = color(230,185,80);
for (int i=0; i<4; i++) {
fill(c);
rect(0,y,width,y+h);
c=brightenColor(c,1.10); // brighten the colour by 10%
y+=h;
}
}

int brightenElement(float element,float percentage)
{
element=(element*percentage);
if (element>255)
element=255;
return (int)element;
}

// brightenColor
// brightens a colour by a percentage
// percentage should be a float e.g. 1.10 to
// brighten by 10%, or 0.75 to darken by 25%
// returns the new colour
color brightenColor(color c,float percentage)
{
int r=brightenElement(red(c),percentage);
int g=brightenElement(green(c),percentage);
int b=brightenElement(blue(c),percentage);
return color(r,g,b);
}

No comments:

Post a Comment