
Background Color, Text Color
On Thu, 12 Jun 2003 21:57:08 -0400, Joseph M. Newcomer
I found the following algorithm in an old MSJ article on drawing
gradient caption bars. (it's also used on a project found on
codeguru.com)
int AfxGetLuminosity(COLORREF color)
{
/* This function determines the luminosity of a color */
/*------Revision History------*/
// - June 13, 2003
// Constants
const int HLSMAX = 240;
const int RGBMAX = 255;
// Step - Get the individual color values
int nRed = GetRValue(color);
int nGreen = GetGValue(color);
int nBlue = GetBValue(color);
// Step - Get the maximum and minimum value of the colors
int nRGBMax = max(max(nRed, nGreen), nBlue);
int nRGBMin = min(min(nRed, nGreen), nBlue);
// Step - Use the "magic" formula
return (((nRGBMax + nRGBMin) * HLSMAX) + RGBMAX) / (2 *
RGBMAX);
Quote:
}
if luminosity returns > 120, use black, else use white. It seems to
work OK for most of the basic colors in CColorDialog, haven't tried
any custom colors yet. Bright green is the color that seems to cause
problems.
Jack
Quote:
>Yes, I tried similar algorithms and got the same problems. I once tried converting to HSB
>and using an HSB contrast function, and the results were actually less satisfactory.
> joe
>>>i.e.
>>>- If the background colour is fairly dark, use white text.
>>>- If the background colour is fairly light, use black text.
>>I've used this in the past :
>>DWORD GetTextColourForBG (DWORD dwBack)
>>{
>> UINT uRed, uGreen, uBlue;
>> uRed = GetRValue (dwBack);
>> uBlue = GetBValue (dwBack);
>> uGreen = GetGValue (dwBack);
>> if ((uRed + uGreen + uBlue) > 384) // three half intensities
>> {
>> return (0);
>> }
>> else
>> {
>> // Greens will look brighter than
>> // the numbers would suggest, so
>> // swap to black early.
>> if (uGreen > 160)
>> return (0);
>> else
>> return (0xFFFFFF);
>> }
>>}
>>Hacky but semi-OK. I tried colour solutions but you always get bogged
>>down in the special cases like blue-green colour blindness and mid
>>range contrast (as Joe suggests). Keep It Simple :-)
>Joseph M. Newcomer [MVP]
>Web: http://www.flounder.com
>MVP Tips: http://www.flounder.com/mvp_tips.htm