将数字转换为颜色

本文关键字:颜色 转换 数字 | 更新日期: 2023-09-27 17:51:24

我正在尝试将整数0到65536转换为c#中的Color对象。最初,我想创建一个包含所有可能的16位颜色的列表,并用整数对它们进行寻址,但这是非常低效的。

我怎样才能得到第I个可能的16位颜色对象?

将数字转换为颜色

一个16位的颜色通常由5位红色,6位绿色和5位蓝色组成:

rrrr rggg gggb bbbb

参考文献:Wikipedia: High color

要将其转换为Color结构所表示的24位颜色,您将提取颜色分量并将其转换为0..255范围:

int red = color >> 11;
int green = (color >> 5) & 63;
int blue = color & 31;
red = red * 255 / 31;
green = green * 255 / 63;
blue = blue * 255 / 31;
Color result = Color.FromArgb(red, green, blue);

. net Color结构体以32位存储颜色。

你需要知道你的16位颜色是如何编码的:

  • R5 G6 B5(5位红色,6位绿色,5位蓝色)
  • A1 R5 G5 B5(1位alpha)
  • 任何其他编码

让我们假设你的16位颜色是A1 R5 G5 B5

目标将是A8 R8 G8 B8

public static Color FromUInt16(UInt16 color)
{
    Int32 fullColor = color;
    Int32 maskA = 32768;    // binary 1 00000 00000 00000
    Int32 maskR = 0x7C00;   // binary 0 11111 00000 00000
    Int32 maskG = 0x3E0;    // binary 0 00000 11111 00000
    Int32 maskB = 0x1F;     // binary 0 00000 00000 11111
    // Mask the whole color with bitmasks to isolate each color.
    // for example : 1 11111 11111 11111 (white) masked 
    //with 0 11111 00000 00000 (red) will give : 0 11111 00000 00000
    Int32 alpha =  ((maskA & fullColor) >> 8);
    Int32 red = ((maskR & fullColor) >> 7);
    Int32 green = ((maskG & fullColor) >> 2);
    Int32 blue = ((maskB & fullColor) << 3);
    // 1 bit alpha encoding.
    // if   alpha = 1
    // then alpha = 11111111
    // else alpha = 00000000
    alpha = alpha > 0 ? 255 : 0;
    // Since the original resolution for each color is 5 bits,
    // and the new resolution is 8 bits, the 3 least significant bits 
    // must be padded with 1's if the 5th bit is 1, otherwise pad them with 0.
    red = (red & 0x8) == 0x8 ? red | 0xF : red;
    green = (green & 0x8) == 0x8 ? green | 0xF : green;
    blue = (blue & 0x8) == 0x8 ? blue | 0xF : blue;
    return Color.FromArgb(alpha,red,green,blue);
}