2012-08-01 92 views
0

我想要一个用户输入十六进制int并使其更暗。有任何想法吗?需要使一个十六进制0xff ******字符串较深(* =任何十六进制字符)

+2

你必须给出一些上下文。数字本身并没有“黑暗”属性。 7不会比13或0xff356483更深。 – Eclipse 2012-08-01 23:02:18

+0

你是否有6字节RRGGBB格式的颜色,你想在保持色调/饱和度的同时降低强度? – 2012-08-01 23:09:07

+0

您的意思是说:“给定一个RGB颜色作为十六进制数,将其转换为代表'较暗'颜色的新十六进制数”?如果是这样,“黑暗”是什么意思?如果颜色已经很暗,如0x00202020怎么办? – 2012-08-01 23:09:53

回答

2

只是做二进制减法:

int red = 0xff0000; 
int darkerRed = (0xff0000 - 0x110000); 
int programmaticallyDarkerRed; 

你甚至可以使其与一个循环较暗:

for(int i = 1; i < 15; i++) 
{ 
    programmaticallyDarkerRed = (0xff0000 - (i * 0x110000)); 
} 

它得到0x000000或黑色越近,越暗它将会。

+0

您可能不应删除旧的答案以发布完全相同的副本。 – Jeffrey 2012-08-01 23:28:25

+2

如果一个答案被拒绝投票,你应该在答案中解决问题,而不是发布一个新问题。 – Jeffrey 2012-08-01 23:30:43

+0

很抱歉,但没有,它没有工作,它适用于一些但不是所有的颜色,这里是他们的列表:\t \t \t \t \t \t公共静态INT紫色= 0xffCC33FF; \t public static int red = 0xffCC0000; \t public static int green = 0xff33CC33; \t public static int blue = 0xff3366FF; \t public static int yellow = 0xffFFFF66; \t public static int pink = 0xFFFF99FF; \t public static int white = 0xffFFFFFF; \t public static int black = 0xff000000; \t public static int gray = 0xff404040; \t public static int lightgrey = 0xffa0a0a0; \t public static int orange = 0xffFF9900; – user1462577 2012-08-01 23:46:51

0

您可以在十六进制值转换为Color,然后变暗Color对象

// Convert the hex to an color (or use what ever method you want) 
Color color = Color.decode(hex); 

// The fraction of darkness you want to apply 
float fraction = 0.1f; 

// Break the color up 
int red = color.getRed(); 
int blue = color.getBlue(); 
int green = color.getGreen(); 
int alpha = color.getAlpha(); 

// Convert to hsb 
float[] hsb = Color.RGBtoHSB(red, green, blue, null); 
// Decrease the brightness 
hsb[2] = Math.min(1f, hsb[2] * (1f - fraction)); 
// Re-assemble the color 
Color hSBColor = Color.getHSBColor(hsb[0], hsb[1], hsb[2]); 

// If you need it, you will need to reapply the alpha your self 

UPDATE

拿回来为十六进制,你可以尝试像

int r = color.getRed(); 
int g = color.getGreen(); 
int b = color.getBlue(); 

String rHex = Integer.toString(r, 16); 
String gHex = Integer.toString(g, 16); 
String bHex = Integer.toString(b, 16); 

String hexValue = (rHex.length() == 2 ? "" + rHex : "0" + rHex) 
       + (gHex.length() == 2 ? "" + gHex : "0" + gHex) 
       + (bHex.length() == 2 ? "" + bHex : "0" + bHex); 

int intValue = Integer.parseInt(hex, 16); 

现在,如果这不是很对,我会看看,看看是否有任何答案的S O或谷歌

+0

但我怎么回到一个十六进制int? 8位 – user1462577 2012-08-01 23:41:27

1

我会用Color.darker

Color c = Color.decode(hex).darker();

+0

但我怎么会将它转换回十六进制int? – user1462577 2012-08-01 23:37:06

+0

@ user1462577您可以使用['Color.toRGB()'](http://docs.oracle.com/javase/7/docs/api/java/awt/Color.html)为您的argb值获取'int' #getRGB()),然后你可以使用['Integer.toHexString()'](http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toHexString(int) )将其转换为十六进制表示。 – Jeffrey 2012-08-01 23:58:13

+0

@Downvoter谨慎解释? – Jeffrey 2012-08-01 23:58:19