且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# - 将ARGB颜色转换为RGB555

更新时间:2023-09-06 16:23:16

A 颜色每像素使用32位:alpha,红色,绿色和蓝色值各8位。 (这意味着每个组件的值范围从0到255.)

A Color uses 32 bits per pixel: 8 bits each for the alpha, red, green, and blue values. (This means that the values for each component can range from 0 to 255.)

A RGB555 颜色每个像素使用5位(没有alpha通道),因此红色,绿色和蓝色都可以从0 -31。

A RGB555 color uses 5 bits per pixel (and has no alpha channel), so red, green and blue can each take a value from 0-31.

要从一个转换到另一个,我们需要将值0-255映射到值0-31。这显然是一个有损的过程;我们根本不能表示每个可能的 Color ,并且许多不同的 Color 值将被映射到相同的 Color555

To convert from one to the other, we need to map the values 0-255 on to the values 0-31. This will obviously be a lossy process; we simply can't represent every possible Color and many different Color values will be mapped to the same Color555.

最简单的映射只是截断,我们除以8并舍弃余数。这将0-7映射到0,8-15到1,...,248-255到31.这可以写为向右向右移位三位。

The simplest mapping is just truncation, where we divide by 8 and discard the remainder. This maps 0-7 to 0, 8-15 to 1, ..., 248-255 to 31. This can be written as a rightwards bitshift by three bits.

然后我们需要将这些值组合成一个16位的值,这是通过将红色和绿色组件向左移动来实现的。

We then need to combine the values into a single 16-bit value, which is accomplished by shifting the red and green components to the left.

基于高位设置alpha通道,因此我们可以以相同的方式向后转换alpha通道。在这种情况下,我们需要将256个可能的值映射到2:0或1.我选择了分割Alpha通道正好一半;还有其他可能的映射。)

(Your sample code appears to be setting the alpha channel based on the high bit, so we can convert the alpha channel backwards in the same manner. In this case, we need to map 256 possible values on to 2: 0 or 1. I've chosen to divide the alpha channel exactly in half; there are other possible mappings.)

将它们放在一起,它应该是:

Putting it all together, it should look like:

public Color555(Color color)
{
    _Value = (ushort) ((color.A >= 128 ? 0x8000 : 0x0000) |
        ((color.R & 0xF8) << 7) | ((color.G & 0xF8) << 2) | (color.B >> 3));
}