Calculating a color gradient
For a recent project I needed some code to calculate a colour gradient for different points on a scatter chart. The class below performs a simple interpolation between two colours, if you feed it a value between 0 and 1.
public class GradientCalculator {
private Color c1;
private Color c2;
public GradientCalculator(Color c1, Color c2) {
this.c1 = c1;
this.c2 = c2;
}
/**
* @param ratio - value between 0 and 1
*/
public Color getColor(double ratio) {
int red = (int) (c1.getRed() * (1 - ratio) + c2.getRed() * ratio);
int green = (int) (c1.getGreen() * (1 - ratio) + c2.getGreen() * ratio);
int blue = (int) (c1.getBlue() * (1 - ratio) + c2.getBlue() * ratio);
int alpha =(int) (c1.getAlpha() * (1 - ratio) + c2.getAlpha() * ratio);
return new Color(red, green, blue, alpha);
}
}
private Color c1;
private Color c2;
public GradientCalculator(Color c1, Color c2) {
this.c1 = c1;
this.c2 = c2;
}
/**
* @param ratio - value between 0 and 1
*/
public Color getColor(double ratio) {
int red = (int) (c1.getRed() * (1 - ratio) + c2.getRed() * ratio);
int green = (int) (c1.getGreen() * (1 - ratio) + c2.getGreen() * ratio);
int blue = (int) (c1.getBlue() * (1 - ratio) + c2.getBlue() * ratio);
int alpha =(int) (c1.getAlpha() * (1 - ratio) + c2.getAlpha() * ratio);
return new Color(red, green, blue, alpha);
}
}
You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply