Home Articles Books Downloads FAQs Tips

Q: Extract the individual red, blue, and green intensities from a TColor object


Answer:

Use the API functions GetRValue, GetBValue, and GetGValue. Here an example that incrementally changes the background color of a form by extracting and then modifying the individual color intensities (note: to use the code, set the Color of form to clBlue, clNavy, or any of the other color constants that are not system color names, such as clBtnFace)

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    BYTE nRed   = GetRValue(Color);
    BYTE nBlue  = GetBValue(Color);
    BYTE nGreen = GetGValue(Color);

    nRed +=10;
    nBlue -=10;
    nGreen *= 1.05;
    Color =(TColor) RGB(nRed, nGreen, nBlue);
}

Note: The Get functions return an intensity between 0 (black) and 255 (max intensity. The return type is BYTE because the individual intensities fit in one byte. When you set an intensity that is less than 0 or greater than 255, the RGB macro chops of the extra bits in your value (it only retains the lower 8 bits of your intensity).

Note: Technically, the Get functions are not really functions, they are C style macros. You can see their implementaion in INCLUDE\WIN32\WINGDI.H. One consequence of using macros is that the functions are not type safe. You can pass a char * to the macros, and they won't warn you that what you are doing doesn't make much sense.



Copyright © 1997-2000 by Harold Howe.
All rights reserved.