| 47 | /// `IllegalArgumentException` when the value is not a recognised color so |
| 48 | /// the caller can choose between a default and a propagated failure. |
| 49 | public static int parse(String value) { |
| 50 | String trimmed = value == null ? "" : value.trim(); |
| 51 | if (trimmed.length() == 0) { |
| 52 | throw new IllegalArgumentException("Empty color"); |
| 53 | } |
| 54 | if (trimmed.charAt(0) == '#') { |
| 55 | return parseHexColor(trimmed.substring(1)); |
| 56 | } |
| 57 | String lower = trimmed.toLowerCase(); |
| 58 | if (lower.startsWith("rgba(") || lower.startsWith("rgb(")) { |
| 59 | int open = trimmed.indexOf('('); |
| 60 | int close = trimmed.lastIndexOf(')'); |
| 61 | if (open < 0 || close < open) { |
| 62 | throw new IllegalArgumentException("Unrecognised color: " + value); |
| 63 | } |
| 64 | List<String> comps = StringUtil.tokenize(trimmed.substring(open + 1, close), ','); |
| 65 | if (comps.size() < 3) { |
| 66 | throw new IllegalArgumentException("Unrecognised color: " + value); |
| 67 | } |
| 68 | int r = parseColorComponent(comps.get(0)); |
| 69 | int g = parseColorComponent(comps.get(1)); |
| 70 | int b = parseColorComponent(comps.get(2)); |
| 71 | int a = 255; |
| 72 | if (comps.size() >= 4) { |
| 73 | a = clamp(Math.round(parseFloat(comps.get(3).trim()) * 255f)); |
| 74 | } |
| 75 | return (a << 24) | (r << 16) | (g << 8) | b; |
| 76 | } |
| 77 | Integer named = NAMED_COLORS.get(lower); |
| 78 | if (named != null) { |
| 79 | return named.intValue(); |
| 80 | } |
| 81 | throw new IllegalArgumentException("Unrecognised color: " + value); |
| 82 | } |
| 83 | |
| 84 | /// Parses a CSS color string into `0xAARRGGBB`, returning `defaultColor` |
| 85 | /// when the value is `null` or not a recognised color. The lenient variant |