1 30 31 34 package com.nightlabs.util; 35 36 import java.awt.Color ; 37 import java.util.regex.Pattern ; 38 39 42 public class ColorUtil 43 { 44 45 protected ColorUtil() 46 { 47 } 48 49 protected static class RGBA { 50 public int r, g, b, a; 51 } 52 53 protected static Pattern SPLIT_RGBA_PATTERN = Pattern.compile( 54 "^\\p{Blank}*|\\p{Blank}*\\{\\p{Blank}*|\\p{Blank}*\\}\\p{Blank}*$|,\\p{Blank}*"); 55 56 protected static RGBA parseRGBA(String color) 57 { 58 RGBA rgba = new RGBA(); 59 String [] parts = SPLIT_RGBA_PATTERN.split(color); 60 if (!"RGBA".equals(parts[1]) && !"RGB".equals(parts[1])) 61 throw new IllegalArgumentException ("color is neither RGB nor RGBA encoded! It must start with 'RGB' or 'RGBA'!"); 62 63 if (parts.length < 5) 64 throw new IllegalArgumentException ("color is incomplete! It must at least contain three decimal numbers specifying red, green and blue! It should specify alpha as forth value."); 65 66 rgba.r = Integer.parseInt(parts[2]); 67 rgba.g = Integer.parseInt(parts[3]); 68 rgba.b = Integer.parseInt(parts[4]); 69 70 if (parts.length >= 6) 71 rgba.a = Integer.parseInt(parts[5]); 72 else 73 rgba.a = 255; 74 75 if (rgba.r < 0 || rgba.g < 0 || rgba.b < 0 || rgba.a < 0) 76 throw new IllegalArgumentException ("color is invalid! One of the values for red, gree, blue or alpha is less than 0!"); 77 78 if (rgba.r > 255 || rgba.g > 255 || rgba.b > 255 || rgba.a > 255) 79 throw new IllegalArgumentException ("color is invalid! One of the values for red, gree, blue or alpha is greater than 255!"); 80 81 return rgba; 82 } 83 84 public static String colorToString(Color color) 85 { 86 return "RGBA{" 87 + color.getRed() + ',' 88 + color.getGreen() + ',' 89 + color.getBlue() + ',' 90 + color.getAlpha() + '}'; 91 } 92 93 100 public static String colorToString(int red, int green, int blue, int alpha) 101 { 102 return "RGBA{" 103 + red + ',' 104 + green + ',' 105 + blue + ',' 106 + alpha + '}'; 107 } 108 109 public static Color stringToColor(String color) 110 { 111 RGBA rgba = parseRGBA(color); 112 return new Color ( 113 rgba.r, 114 rgba.g, 115 rgba.b, 116 rgba.a); 117 } 118 119 130 } 131 | Popular Tags |