public class Color {
/** The colors are numbers between 0 and 255, inclusive. */
private int red;
private int green;
private int blue;
/** A helper function that returns a number in the 0..255 range.
* @param x the number
* @return x if its in 0..255, 0 if x is negative, 255 otherwise
*/
private int boundColor (int x) {
if (x < 0 ) return 0;
if (x > 255) return 255;
return x;
}
public Color(int red, int green, int blue) {
this.red = boundColor(red);
this.green = boundColor(green);
this.blue = boundColor(blue);
}
public Color() {
this(0,0,0);
}
/** Creates a color, assumes that the arguments are values between 0 and 1.
* @param red
* @param green
* @param blue
*/
public Color (double red, double green, double blue) {
this.red = boundColor((int) (red * 255));
this.green = boundColor((int) (green * 255));
this.blue = boundColor((int) (blue * 255));
}
public Color(String name) {
this(0,0,0); //set all to 0
if (name.equalsIgnoreCase("red")) {
red = 255;
}
else if (name.equalsIgnoreCase("green")) {
green = 255;
}
else if (name.equalsIgnoreCase("blue")) {
blue = 255;
}
}
/** Turns in into a padded hex string. Assumes 0<= n <= 255.
* @param n the number
* @return a string representation of the number, of 2 characters
*/
private String makeHexString(int n) {
String value = Integer.toHexString(n);
if (value.length() < 2) {
return "0" + value;
}
return value;
}
/**
* Returns a color halfway between this one and other
* @param other
* @return a new color that is the average (on RGB) of this color and other
*/
public Color mixWith(Color other) {
Color newColor = new Color((red + other.red) / 2, (green + other.green) / 2, (blue + other.blue) / 2);
return newColor;
}
public String toString() {
return "#" + makeHexString(red) + makeHexString(green) + makeHexString(blue);
}
/**
* @param args
*/
public static void main(String[] args) {
//a constructor with all ints arguments, each is a number between 0 and 255.
Color red = new Color(255,0,0);
System.out.println(red);
//a constructor that understands "red", "green" and "blue".
Color blue = new Color("blue");
System.out.println(blue);
//a constructor with all doubles as arguments, each is a number between 0 and 1.
Color green = new Color(0.0, 1.0, 0.0);
System.out.println(green);
//if a number is out of range you push it back into the range!
Color reallyGreen = new Color(0.0, 100, 0.0);
System.out.println(reallyGreen);
//Mix colors by simply taking the average of each component (RGB).
Color purple = red.mixWith(blue);
System.out.println("purple=" + purple);
purple = purple.mixWith(red);
System.out.println(purple);
purple = purple.mixWith(red);
System.out.println(purple);
}
}
Thursday, October 7, 2010
HW 4 Solution
Below is my solution to HW 4: Colors
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment