WIN32中颜色值(COLORREF)与.NET中颜色值(Color)的转换【转】

如果使用mfc与.net混合编程,就会遇到这个问题,通过mfc编写的控件,由.net调用,则控件中背景色的设置,需要颜色的转换。

colorref类型颜色的值colorref cr=rgb(123,200,12); 

其中的r、g、b三个分量的排列顺序是bgr。

.net中通过数据类型color表示颜色,该类有一个函数fromargb(int,int,int),可以通过输入rgb三个值得到一个color类型的颜色。同时也有一个toargb()函数,得到一个32位的整数值,

32 位 argb 值的字节顺序为 aarrggbb。由 aa 表示的最高有效字节 (msb) 是 alpha 分量值。分别由 rr、gg 和 bb 表示的第二、第三和第四个字节分别为红色、绿色和蓝色颜色分量

了解了上面的内容,颜色的转换就很简单了。

1、从color到colorref

            int ncolor = crcolor.toargb();
            int blue = ncolor & 255;
            int green = ncolor >> 8 & 255;
            int red = ncolor >> 16 & 255;
           
            //注意colorref中颜色的排列是 bgr,而通过color.toargb()得到的数值中颜色排列是aarrggbb
            int ncolorref = blue << 16 | green << 8 | red;

2、从colorref到color(注意colorref中颜色的排列是bgr,红色分量在最后面)

int red=ncolorref & 255;

int green= ncolorref >> 8 & 255;

int blue= ncolor ref>> 16 & 255;

color crcolor=color.fromargb(red,green,blue);

或者直接通过下面的代码:

 color.fromargb(ncolorref & 255, ncolorref >> 8 & 255, ncolor ref>> 16 & 255);

注:上面的代码使用c#编写。

原文地址:https://www.cnblogs.com/zhaobl/p/1663412.html