/**
*
* @author jt.tao
* 2010-07-18
*/
public class ColorPicker {
public String pad(String num, int totalChars) {
String pad = "0";
num = num + "";
while (num.length() < totalChars) {
num = pad + num;
}
return num;
}
public String changeColor(String color, float ratio, boolean darker) {
// Trim trailing/leading whitespace
color = color.replaceAll("^\\s*|\\s*$|\\s*","");
// Expand three-digit hex
color = color.replaceAll("^#?([a-f0-9])([a-f0-9])([a-f0-9])$","#$1$1$2$2$3$3");
// Calculate ratios
float difference = Math.round(ratio * 256) * (darker ? -1 : 1);
// Determine if input is RGB(A)
String regex = "^rgba?\\(\\s*"
+ "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" + "\\s*,\\s*"
+ "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" + "\\s*,\\s*"
+ "(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])" + "(?:\\s*,\\s*"
+ "(0|1|0?\\.\\d+))?" + "\\s*\\)$";
Matcher matcher1 = Pattern.compile(regex).matcher(color);
String[] rgb = null;
if (matcher1.find()) {
rgb = color.substring(color.indexOf("(") + 1,color.lastIndexOf(")")).split(",");
}
float alpha=Float.MIN_VALUE;
if(rgb != null && rgb.length == 4){
alpha=Float.parseFloat(rgb[3]);
}
// Convert hex to decimal
String[] decimal = null;
if (rgb != null && rgb.length >= 3) {
decimal = new String[] { rgb[0], rgb[1], rgb[2] };
} else {
String reg = "^#?([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])([a-f0-9][a-f0-9])$";
Matcher matcher = Pattern.compile(reg).matcher(color);
if(matcher.find()){
String decimalstr = "";
String _c=matcher.group().replace("#","");
for (int j = 0,l=3; j < l; j++) {
decimalstr += Integer.parseInt(_c.substring(j*2,j*2+2),16) + ((j == l - 1) ? "" : ",");
}
decimal = decimalstr.split(",");
}
}
return (rgb != null) ? "rgb"
+ (alpha>Float.MIN_VALUE ? "a" : "")
+ "("
+ max_min(darker, Integer.parseInt(decimal[0], 10) + difference)
+ ", "
+ max_min(darker, Integer.parseInt(decimal[1], 10) + difference)
+ ", "
+ max_min(darker, Integer.parseInt(decimal[2], 10) + difference)
+ (alpha>Float.MIN_VALUE ? ","+alpha : "") + ")"
:
// Return hex
"#"+
pad(Integer.toHexString(max_min(darker,(Integer.parseInt(decimal[0], 10) + difference))), 2)+
pad(Integer.toHexString(max_min(darker,(Integer.parseInt(decimal[1], 10) + difference))), 2)+
pad(Integer.toHexString(max_min(darker,(Integer.parseInt(decimal[2], 10) + difference))), 2);
}
public String lighterColor(String color, float ratio) {
return changeColor(color, ratio, false);
}
public String darkerColor(String color, float ratio) {
return changeColor(color, ratio, true);
}
public Integer max_min(boolean darker, float f) {
if (darker) {
return (int) Math.max(f, 0) ;
} else {
return (int) Math.min(f, 255);
}
}
public static void main(String[] args) {
ColorPicker c = new ColorPicker();
String darker = c.darkerColor("rgb(80, 88, 25)", .2f);
String lighter = c.lighterColor("rgba(80, 88, 255, .5)", .3f);
System.out.println("darker=" + darker);
System.out.println("lighter=" + lighter);
}
}
转载于:https://www.cnblogs.com/angelbird/archive/2011/07/20/2111838.html