无法将青色的整数颜色转换为RGB

时间:2014-08-28 19:02:13

标签: java colors rgb modulo modulus

有一种简单的算法可以将整数值转换为integer to rgb之间0-255之间的三个数字的RGB值。我从Android Colors得到了整数。我甚至跑了:

System.out.println(Color.decode("-16711681"));

,答案是java.awt.Color [r = 0,g = 255,b = 0],这是预期的。

我确实在第一步有问题,-16711681%256是255,我希望红色为0。在Java中我编码:

System.out.println(-16711681 % 256);

我得-1,这意味着我必须加256,我的红颜色是255.有人能帮帮我吗?

2 个答案:

答案 0 :(得分:2)

那是因为你的号码不是像你的gamedev链接那样的ABGR打包的int,而是一个ARGB打包的int。

Color.decode(int)想要采用以下格式的颜色:

0xAARRGGBB

其中AA是透明度,RR是红色,GG是绿色,BB是蓝色。执行color % 256时,会返回颜色的蓝色(BB)部分。

如果我们使用Integer.toHexString(-16711681)查看颜色,我们会得到:

 Color:   ff00ffff
(Format:  AARRGGBB)

相当于Color[r=0,g=255,b=255]

如果你想读取红色值,你需要先将它移开:

(color >> 16) & 0xFF

答案 1 :(得分:1)

让我们说x=-16711681

x的二进制值为11111111000000001111111111111111

Integer c = new Integer(-16711681);
System.out.println(Integer.toBinaryString(x));

现在,根据Java Docs获取Red Value我们需要从16-23 bits中提取x

enter image description here


Qn:如何从32位整数中的16-23位提取8位?

答案: x = (x >> 16) & 0xFF;


// Bits 24-31是alpha,16-23是红色,8-15是绿色,0-7是蓝色

因此,Color.decode("-16711681"));相当于

System.out.println(((-16711681 >> 16) & 0xFF) + ":"
                + ((-16711681 >> 8) & 0xFF) + ":" + ((-16711681 >> 0) & 0xFF));

输出

0:255:255

请注意 System.out.println(Color.decode("-16711681"));输出

java.awt.Color[r=0,g=255,b=255]