Code with Finding: |
class WebColors {
/**
* Gives you a BaseColor based on a name.
*
* @param name
* a name such as black, violet, cornflowerblue or #RGB or #RRGGBB
* or RGB or RRGGBB or rgb(R,G,B)
* @return the corresponding BaseColor object. Never returns null.
* @throws IllegalArgumentException
* if the String isn't a know representation of a color.
*/
public static BaseColor getRGBColor(String name)
throws IllegalArgumentException {
int[] c = { 0, 0, 0, 255 };
name = name.toLowerCase();
boolean colorStrWithoutHash = missingHashColorFormat(name);
if (name.startsWith("#") || colorStrWithoutHash) {
if (!colorStrWithoutHash) {
name = name.substring(1); // lop off the # to unify hex parsing.
}
if (name.length() == 3) {
String s = name.substring(0, 1);
c[0] = Integer.parseInt(s+s, 16);
String s2 = name.substring(1, 2);
c[1] = Integer.parseInt(s2+s2, 16);
String s3 = name.substring(2);
c[2] = Integer.parseInt(s3+s3, 16);
return new BaseColor(c[0], c[1], c[2], c[3]);
}
if (name.length() == 6) {
c[0] = Integer.parseInt(name.substring(0, 2), 16);
c[1] = Integer.parseInt(name.substring(2, 4), 16);
c[2] = Integer.parseInt(name.substring(4), 16);
return new BaseColor(c[0], c[1], c[2], c[3]);
}
throw new IllegalArgumentException(MessageLocalization.getComposedMessage("unknown.color.format.must.be.rgb.or.rrggbb"));
}
else if (name.startsWith("rgb(")) {
StringTokenizer tok = new StringTokenizer(name, "rgb(), \t\r\n\f");
for (int k = 0; k < 3; ++k) {
String v = tok.nextToken();
if (v.endsWith("%"))
c[k] = Integer.parseInt(v.substring(0, v.length() - 1)) * 255 / 100;
else
c[k] = Integer.parseInt(v);
if (c[k] < 0)
c[k] = 0;
else if (c[k] > 255)
c[k] = 255;
}
return new BaseColor(c[0], c[1], c[2], c[3]);
}
if (!NAMES.containsKey(name))
// TODO localize this error message.
throw new IllegalArgumentException("Color '" + name
+ "' not found.");
c = NAMES.get(name);
return new BaseColor(c[0], c[1], c[2], c[3]);
}
}
|