Graph Workbench SPI :: Gradient Color Model and Initialization

Gradient Color Model

All of this looks pretty darned boring with just flat color. One alternative to the approach of returning a single color under certain conditions is to calculate the color on the fly. This is not hard to do, but it would be nice to give the user some input into what sort of colors are used. This is where the ColorModel comes in to play, allowing users to specify some simple or complex gradients. Just created a parameter with the ColorModel type and the Graph Workbench will do all the hard work of capturing this complexity.

import com.stimware.graphworkbench.spi.Algorithm;
import com.stimware.graphworkbench.spi.ColorModel;
import com.stimware.graphworkbench.spi.Description;
import com.stimware.graphworkbench.spi.Parameter;
import java.awt.Color;

@Description(name="Tutorial 1-5")
public class Tutorial_1_5 implements Algorithm {

    ColorModel color;

    @Parameter(defaultValue="(length=1,start=yellow,end=red)", label="Square Color")
    public void setColor(ColorModel color) {
        this.color = color;
    }

    public void init() {
        color.setPeriod(10);
    }

    public Color calculate(double x, double y) {

        // Is this point within the square?
        if (x > -0.5 && x < 0.5) {
            if (y > -0.5 && y < 0.5) {
                double offset = x + 0.5;
                int index = (int)(offset * 10);
                return color.getColor(index);
            }
        }

        return Color.BLACK;
    }
}

The result of this algorithm is the same square but with a more visually pleasing gradient color starting from yellow on the left fading through to red on the right. The user can make any adjustments they like to this.

The important thing to know about a ColorModel is that they act as a function, giving you a color for any integer value passed in to them. Think of it as a series (or array) of colors of a set length, you just need to specify the index of the required color. This series is periodic, so will repeat after the highest index. For this reason you need to specify a period for the ColorModel.

Initialization

We have also sneakily introduced a new concept in this tutorial - initialization. You have the option of providing an init method which will be called once after the parameters have been passed and before the first call to your calculate method. This is the best place to set the period for any ColorModel parameters, which may also be defined as a parameter.

You may also want to perform any set up calculations here that may assist in your per-coordinate calculations later on. Feel free to set the values of any instance variables at this point.