An Introduction to colorLib
Posted on 2010-11-05 by Jan Vantomme
Tags:
colorlib, processing
Some time ago, Andreas Köberle and I made a library for Processing to fetch colors from web services like Adobe Kuler and Colourlovers so we can use them in our work. You can also create color palettes from images and .cs
or .act
files with this library. I'm going to cover the basics of using colorLib in this article.
If you don't have colorLib yet, you can download it on Google Code and install it in the libraries folder in your Processing sketchbook. The next thing you need to do is import the library to your sketch so you can start using it.
import colorLib.calculation.*;
import colorLib.*;
import colorLib.webServices.*;
Creating a Palette
The most basic method to create a palette is to declare a Palette variable before and initialize the object in the setup()
method. Right after you've initialized the Palette object, you can start adding colors with the addColor()
method.
Palette p;
void setup()
{
size(450, 300);
p = new Palette(this);
p.addColor(color(255, 106, 0));
}
I usually move the task of creating a palette and filling it with colors to a separate function to keep my setup()
method a little cleaner. This also makes the management of colors throughout my sketches a little easier. If you add this function to a separate tab in Processing, you'll also be able to reuse this palette in other sketches.
void setupColors()
{
p = new Palette(this);
p.addColor(color(255, 106, 0));
p.addColor(color( 71, 69, 80));
p.addColor(color(164, 223, 36));
p.addColor(color( 19, 34, 41));
p.addColor(color( 95, 133, 117));
}
Using the Palette in your Sketch
If you want to get a color from your new palette, you need to call the getColor()
method. This method requires an integer to get a color at a certain position. If you want the first color of the palette, you'll use p.getColor(0);
. A handy method to loop through all colors of the palette is the totalSwatches()
method.
for (int i = 0; i < p.totalSwatches(); i++) {
fill(p.getColor(i));
rect(i*90, 0, 90, height);
}
Running the sketch should give you the following result.
Sorting Colors
colorLib also provides a few methods to sort the colors in your palette by hue, saturation, luminance or proximity. To sort colors by hue, you simply call the sortByHue()
method. The image below shows you the original palette and the same palette sorted by hue.
Download
Download the full code for this tutorial: colorlib_basics.zip.