Creating Gradients with colorLib
Posted on 2010-12-24 by Jan Vantomme
Tags:
colorlib, processing, tutorial
colorLib has a class to create gradients from an array of colors or a Palette object. The gradient class extends the Palette class, so all methods from that class can be used on the gradient object you create.
There are four different constructors you can use to create a Gradient object. In this article, I'm going to show you how you to use them, and draw the gradients to the screen. Note that a gradient object is just a palette that stores all colors from the gradient. The library doesn't have methods to draw gradients to the screen.
Creating a Gradient From an Array of Colors
First, you'll need to declare a variable of type Gradient. I'll usually name it g
.
Gradient g;
Second thing to do is creating an array of colors.
color[] c = new color[2];
c[0] = color(255, 0, 0);
c[1] = color(255, 255, 0);
The following piece of code will take the two colors from the array and calculate the 120 steps between them.
g = new Gradient(this, c, 120);
You can draw a gradient by accessing the colors from the gradient object. I usually don't draw gradients to the screen but use the object to animate the color of an object over a certain time.
for (int i = 0; i < g.totalSwatches(); i++) {
stroke( g.getColor(i) );
line(0, i, width, i);
}
Wrap the colors
If you want your gradient to end with the same color as the startcolor, you can use a fourth parameter on the constructor. Use true
if you want to wrap the gradient, false
if you want a normal gradient.
g = new Gradient(this, c, 120, true);
Creating a Gradient From a Palette Object
Creating a gradient from a colorLib Palette object works the same way. In stead of an array with colors, you'll just add a Palette object as a parameter in the constructor. Be careful when you generate a palette with random colors. The results might look ugly...
p = new Palette(this);
for (int i = 0; i < 5; i++) {
p.addColor( color(random(255), random(255), random(255) ) );
}
g = new Gradient(p, 450);
Wrap the colors
You can also wrap the colors of the gradient when you create one from a Palette object.
g = new Gradient(p, 450, true);
Downloads
Download all gradient examples from this tutorial. Download [colorLib](https://code.google.com/p/colorlib/ at Google Code).
If you create images with colorLib, please add them to our Flickr group.