跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

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#编写。

相关文章