如何将Color转换为Char?

时间:2015-11-21 02:19:20

标签: c# unicode colors char

我发现这个代码将Unicode字符转换为颜色,例如如果字符A,它将使rgb 0 8 4。 如何将颜色转换为字符,如果rgb为0 8 4则会产生A?

        const int RedMask = 0xF8;
        const int GreenMask = 0xF8;
        const int BlueMask = 0xFC;
        const int RedShift = 8;
        const int GreenShift = 3;
        const int BlueShift = 2;

        int val = ch;
        int r = (val >> RedShift) & RedMask;
        int g = (val >> GreenShift) & GreenMask;
        int b = (val << BlueShift) & BlueMask;

        Color clr = Color.FromArgb(r, g, b);

1 个答案:

答案 0 :(得分:1)

.Net中你的字符长2个字节 所以,让我们说它是0xFFFF

RedMask =   0b11111000    
GreenMask = 0b11111000    
BlueMask =  0b11111100

让我们在第一位(最左边)调用最重要的位

这就是我们获得红色

的方式
Right shift by 8 bits. You get  0b11111111(11111111) <-- this number in parenthesis get pushed off    
                       mask it  0b11111000
                       result   0b11111000 <-- our 1st to 5th bit are preserved

所以我们从Red 1st-5th获得第1-5位

这就是我们获得绿色

的方式
Right shift by 3 bits. You get 0b1111111111111 (111)
                       mask it 0b0000011111000
                        result 0b0000011111000 <-- That's our 6th to 10th bit.

现在我们从Green的第1至第5位获得第6-10位

最后是蓝色

Left shift by 2 bits. You get (11) 0b111111111111111100
                      mask it      0b000000000011111100
                      You get      0b000000000011111100 <-- That's the rest of the bits here :-)

我们从绿色位第1至第6位获得第11-16位

=================================
现在我们把所有这些放在一起我们可以通过将红色的第1至第5位拼接为绿色的第1至第5位,蓝色的第1至第6位来重新组合原始值。像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Drawing;
using System.Text;

namespace WindowsFormsApplication1
{
    static class Program
    {

        static void Main()
        {
            Color color = Char2Color('A');
            char ch = Color2Char(color);

        }

        static char Color2Char(Color c)
        {
            Byte[] result = {0x00,0x00};

            var red = (c.R >> 3) ;
            var green = (c.G >> 3) ;
            var blue = (c.B >> 2);

            result[0] = (byte)(red << 3);
            result[0] = (byte)(result[0] + (green >> 2));
            result[1] = (byte)(green << 6);
            result[1] = (byte)(result[1] + blue);
            Array.Reverse(result);
            return BitConverter.ToChar(result,0);
        }

        static Color Char2Color(char ch)
        {
            const int RedMask = 0xF8;
            const int GreenMask = 0xF8;
            const int BlueMask = 0xFC;
            const int RedShift = 8;
            const int GreenShift = 3;
            const int BlueShift = 2;

            int val = ch;
            int r = (val >> RedShift) & RedMask;
            int g = (val >> GreenShift) & GreenMask;
            int b = (val << BlueShift) & BlueMask;

            return Color.FromArgb(r, g, b);
        }

    }
}