// ColorScale.java // A solution to CS 10 assignment 2, part 1, Fall 2008. // cmc, 8/14/08 import java.awt.Color; /** Represents an n-color scale as a smooth transition between the two terminal colors in the scale. */ public class ColorScale { private Color[] levels; /** Constructs a default (gray) scale from white to black with 10 levels. */ public ColorScale() { this(Color.WHITE, Color.BLACK, 10); } /** Constructs a scale from first to last values specified, with the specified number of levels. @param first the first color value. @param last the last color value. @param size the number of levels - assumed to be > 0. */ public ColorScale(Color first, Color last, int size) { levels = new Color[size]; setLevels(first, last); } /** Returns a reference to the specified color level. @param level the color level to get - assumed to be in range of 0 to size()-1. @return color value at specified level. */ public Color get(int level) { return levels[level]; } /** Returns the size of the scale. @return the number of levels in this scale. */ public int size() { return levels.length; } // utility sets the levels private void setLevels(Color first, Color last) { int n = levels.length; levels[0] = first; levels[n-1] = last; int firstRed = first.getRed(), firstGreen = first.getGreen(), firstBlue = first.getBlue(); double dRed = (double)(last.getRed() - firstRed) / (n - 1), dGreen = (double)(last.getGreen() - firstGreen) / (n - 1), dBlue = (double)(last.getBlue() - firstBlue) / (n - 1); for (int i=1; i < n-1; i++) levels[i] = new Color( (int)(firstRed + (i * dRed)), (int)(firstGreen + (i * dGreen)), (int)(firstBlue + (i * dBlue)) ); } }