Java 颜色将 RGB 编码为单个整数?
Java Color encode RGB into single integer?
我正在阅读 "Java The Complete Reference Ninth Edition",作者给出了这个用单个整数创建 Color 对象的示例,该整数对 RGB 值进行编码,他说:
The integer is organized with red in bits 16 to 23, green in bits
8 to 15, and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
0xff000000 in hexadecimal is equivalent to 0b11111111000000000000000000000000 in binary
这是一个 32 位整数...
我理解按位操作,但我不明白的是:
数字开头的那些有什么用?为什么不以零开头
我想你的意思是问为什么0xff000000被添加到聚会中。
它确实取决于实现。
我的猜测是两个选项之一:
1.颜色对这些位没有任何影响,为了安全起见,将不相关的位设置为 1(因此溢出红色与不溢出没有任何不同)。
2. 那就是alpha通道(这个比前者更有意义)
编辑:
现在我意识到你在谈论 awt Color 对象,所以正确的答案是选项 no。 2.
The Javadocs for Color
说明 Java Color
class 包含 alpha 通道和 RGB——因此以全零开头的颜色将是完全透明的. 0xff000000
代表的颜色是不透明黑色。
在这种情况下,作者当然犯了错误。单参数构造函数忽略高字节。相反,如果他想指定 alpha(或者更简单地说,new Color(0xc0, 0, 0, 0xff)
),它应该使用 new Color(0xffc00000, true)
。
我正在阅读 "Java The Complete Reference Ninth Edition",作者给出了这个用单个整数创建 Color 对象的示例,该整数对 RGB 值进行编码,他说:
The integer is organized with red in bits 16 to 23, green in bits 8 to 15, and blue in bits 0 to 7. Here is an example of this constructor:
int newRed = (0xff000000 | (0xc0 << 16) | (0x00 << 8) | 0x00);
Color darkRed = new Color(newRed);
0xff000000 in hexadecimal is equivalent to 0b11111111000000000000000000000000 in binary
这是一个 32 位整数... 我理解按位操作,但我不明白的是:
数字开头的那些有什么用?为什么不以零开头
我想你的意思是问为什么0xff000000被添加到聚会中。
它确实取决于实现。
我的猜测是两个选项之一:
1.颜色对这些位没有任何影响,为了安全起见,将不相关的位设置为 1(因此溢出红色与不溢出没有任何不同)。
2. 那就是alpha通道(这个比前者更有意义)
编辑:
现在我意识到你在谈论 awt Color 对象,所以正确的答案是选项 no。 2.
The Javadocs for Color
说明 Java Color
class 包含 alpha 通道和 RGB——因此以全零开头的颜色将是完全透明的. 0xff000000
代表的颜色是不透明黑色。
在这种情况下,作者当然犯了错误。单参数构造函数忽略高字节。相反,如果他想指定 alpha(或者更简单地说,new Color(0xc0, 0, 0, 0xff)
),它应该使用 new Color(0xffc00000, true)
。