CreateSolidBrush using hex values of color

1.3k views Asked by At

how shall I create brush in mfc application using CreateSolidBrush method with given any hex value for color.

3

There are 3 answers

1
void On
CBrush newBrush;
COLORREF color = 0xFF00FFFF;  
newBrush.CreateSolidBrush(color);

Hope this helps.

1
Anoop Kumar On

I found the solution.

#define GET_RVAL(num) (num & 0xff0000) >> 16
#define GET_GVAL(num) (num & 0x00ff00) >> 8
#define GET_BVAL(num) (num & 0x0000ff)

create brush using

hBrush = CreateSolidBrush(COLORREF(RGB(GET_RVAL(0xbfbfbf), GET_GVAL(0xbfbfbf), GET_BVAL(0xebfbfbf))));
0
IInspectable On

CreateSolidBrush takes an argument of type COLORREF. A COLORREF is an alias for a DWORD, so you could simply assign a value to it:

COLORREF color = 0xFF00FF;
HBRUSH hbr = ::CreateSolidBrush( color );

Make sure to adhere to the documented contract:

The high-order byte must be zero.

A safer alternative would be to use the RGB macro instead:

COLORREF color = RGB( 0xFF, 0x0, 0xFF );
HBRUSH bhr = ::CreateSolidBrush( color );

The RGB macro ensures, that the resulting COLORREF value conforms to the required memory layout.


If you need to extract the individual color components from a COLORREF (or DWORD) argument, you can use the GetRValue, GetGValue, and GetBValue macros:

DWORD dwCol = 0xFF00FF;
BYTE r = GetRValue( dwCol );
BYTE g = GetGValue( dwCol );
BYTE b = GetBValue( dwCol );

While this does work, it introduces architecture specific code. At that point you could simply use the initial DWORD in place of a COLORREF (as illustrated in my first paragraph).