Click here to Skip to main content
16,013,730 members
Articles / Programming Languages / C++
Article

Contrasting Colors

Rate me:
Please Sign up or sign in to vote.
4.08/5 (16 votes)
4 May 20042 min read 167.3K   2.1K   30   37
New method of calculating a contrasting color for a given color
Image 1

Introduction

The conventional way of calculating a contrasting color is to XOR the given color by 0xFFFFFF (or &HFFFFFF). However, the contrasting color obtained in this way may sometimes be similar to the original color, and our eyes can't really differentiate between the two distinctively. Thus this conventional way is not good enough. For example, grey, having the hex value of 0x808080, when XORed with 0xFFFFFF, gives 0x7F7F7F, which is very close to the original color.

I have come up with a new and simple solution that is based on this conventional method. This solution calculates a better contrasting color, but note that it is not always perfect. (Note: I'm not sure whether there already exists such a method).

The solution

This method works by testing whether each of the components (namely red, green, and blue) of the given color is close to 0x80 (128 in decimal). The closeness is defined by the compile time macro TOLERANCE, which is simply a value. If all the components are close to 0x80, then the contrasting color calculated using the old method will not be a good contrast to the original color. The new method overcomes this problem by adding 0x7F7F7F to the given color, and then to prevent overflow (because color values range only from 0x000000 to 0xFFFFFF), the result is ANDed with 0xFFFFFF.

Using the code

The main thing about this project is the function CalcContrastingColor, which is presented below.

At run time, click the "Background..." button to select a background color. Then the program will display a text using the calculated contrasting color. You can also change the font of the text.

// crBG is in 0xRRGGBB or 0xBBGGRR format.
INT CalcContrastColor (INT crBg){

    if (
        abs(((crBg ) & 0xFF) - 0x80) <= TOLERANCE &&
        abs(((crBg >> 8) & 0xFF) - 0x80) <= TOLERANCE &&
        abs(((crBg >> 16) & 0xFF) - 0x80) <= TOLERANCE

    ) return (0x7F7F7F + crBg) & 0xFFFFFF;

    else return crBg ^ 0xFFFFFF;
}

History

Improvements in version 2:
  • Display the outputs as shown in the above image.
  • Some text included in order to let user decide better whether it is a good contrasting color.
  • Windows XP theme compatible.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here



Comments and Discussions

 
GeneralContrasting color? What's new Pin
asnaghi8-Jul-04 23:02
asnaghi8-Jul-04 23:02 
GeneralRe: Contrasting color? What's new Pin
btoum.roumada12-Jul-04 8:40
btoum.roumada12-Jul-04 8:40 
GeneralRe: Contrasting color? What's new Pin
asnaghi14-Jul-04 20:29
asnaghi14-Jul-04 20:29 
These are the functions used for computing contrasting color. They are a bit more complex than the function presented in the article, but they work better.;)
//-------------------------------------------------------------------------//
// Convert an RGB color-space format to HSB color-space format             //
//                                                                         //
// RGB format 0x00BBGGRR                                                   //
// HSB format 0x00HHSSBB                                                   //
//                                                                         //
//-------------------------------------------------------------------------//
COLORREF SfxColorRGBtoHSB(COLORREF color)
{
	int		nHue, nSat, nBri;

	SfxRGBtoHSB(GetRValue(color), GetGValue(color), GetBValue(color),
				&nHue, &nSat, &nBri);

	return HSB(nHue,nSat,nBri);
}

//-------------------------------------------------------------------------//
// Convert an HSB color-space format to RGB color-space format             //
//                                                                         //
// RGB format 0x00BBGGRR                                                   //
// HSB format 0x00HHSSBB                                                   //
//                                                                         //
//-------------------------------------------------------------------------//
COLORREF SfxColorHSBtoRGB(COLORREF color)
{
	int		nRed, nGreen, nBlue;

	SfxHSBtoRGB(GetHValue(color), GetSValue(color), GetLValue(color),
				&nRed, &nGreen, &nBlue);
	return RGB(nRed,nGreen,nBlue);
}

//-------------------------------------------------------------------------//
// Convert the RGB components into HSB components                          //
//                                                                         //
// red, green, blue values are from 0 to 255                               //
// hue = [0,240], sat = [0,100]%, bri = [0,100]%                           //
//                                                                         //
//-------------------------------------------------------------------------//
void SfxRGBtoHSB(int nRed, int nGreen, int nBlue, int *nHue, int *nSat, int *nBri)
{
	double	dRed, dGreen, dBlue;
	double	dHue, dSat, dBri;
	double	dMin, dMax, dDelta;

	dRed = (double)nRed/255.0;
	dGreen = (double)nGreen/255.0;
	dBlue = (double)nBlue/255.0;
	dMin = min(dRed,dGreen);
	dMin = min(dMin,dBlue);
	dMax = max(dRed,dGreen);
	dMax = max(dMax,dBlue);
	dBri = dMax;
	if( dMax == dMin )
	{
		// achromatic color (i.e. grey, black or white)
		// r = g = b = x		
		// sat = 0, bri = x*100, hue is undefined
		*nSat = 0;
		*nHue = HUE_UNDEF;
		*nBri = (int)(dBri * 100.0);
		return;
	}
	dDelta = dMax - dMin;
	dSat = dDelta / dMax;
	if( dRed == dMax ) dHue = (dGreen - dBlue) / dDelta;				// between yellow & magenta
	else if( dGreen == dMax ) dHue = 2.0 + (dBlue - dRed) / dDelta;		// between cyan & yellow
	else dHue = 4.0 + (dRed - dGreen) / dDelta;							// between magenta & cyan
	dHue *= 40.0;
	if( dHue < 0 ) dHue += 240.0;
	*nHue = (int)dHue;
	*nSat = (int)(dSat * 100.0);
	*nBri = (int)(dBri * 100.0);
}

//-------------------------------------------------------------------------//
// Convert the HSB components into RGB components                          //
//                                                                         //
// red, green, blue values are from 0 to 255                               //
// hue = [0,240], sat = [0,100]%, bri = [0,100]%                           //
//                                                                         //
//-------------------------------------------------------------------------//
void SfxHSBtoRGB(int nHue, int nSat, int nBri, int *nRed, int *nGreen, int *nBlue)
{
	int		nSector;
	double	dFract, dVal1, dVal2;
	double	dRed, dGreen, dBlue;
	double	dHue, dSat, dBri;

	if( (nSat == 0) || (nHue == HUE_UNDEF) )
	{
		// achromatic (grey, black or white)
		*nRed = *nGreen = *nBlue = (nBri * 255)/100;
		return;
	}

	dHue = (double)nHue;
	dSat = (double)nSat/100.0;
	dBri = (double)nBri/100.0;

	dHue /= 40.0;
	nSector = (int)floor(dHue);			// sector 0 to 5
	dFract = dHue - floor(dHue);		// factional part of hue
	if( !(nSector & 1) ) dFract = 1.0 - dFract;
	dVal1 = dBri * (1.0 - dSat);
	dVal2 = dBri * (1.0 - dSat * dFract);
	switch( nSector )
	{
	case 0: dRed = dBri;	dGreen = dVal2;		dBlue = dVal1;	break;
	case 1: dRed = dVal2;	dGreen = dBri;		dBlue = dVal1;	break;
	case 2: dRed = dVal1;	dGreen = dBri;		dBlue = dVal2;	break;
	case 3: dRed = dVal1;	dGreen = dVal2;		dBlue = dBri;	break;
	case 4: dRed = dVal2;	dGreen = dVal1;		dBlue = dBri;	break;
	case 5: dRed = dBri;	dGreen = dVal1;		dBlue = dVal2;	break;
	}
	*nRed = (int)(dRed * 255.0);
	*nGreen = (int)(dGreen * 255.0);
	*nBlue = (int)(dBlue * 255.0);
}

//-------------------------------------------------------------------------//
// Create a color that contrast a given color                              //
// This algorithm is taken from my research on color science               //
//-------------------------------------------------------------------------//
COLORREF SfxContrastingColor(COLORREF color, int nThreshold)
{
	int		nOrigLum, nCalcLum, nLoop;
	int		nHue, nSat, nBri;
	int		nRed, nGreen, nBlue;

	nRed = GetRValue(color);
	nGreen = GetGValue(color);
	nBlue = GetBValue(color);
	nOrigLum = LUMINANCE(nRed,nGreen,nBlue);

	SfxRGBtoHSB(nRed, nGreen, nBlue, &nHue, &nSat, &nBri);

	if( nHue == HUE_UNDEF )
	{
		nRed = nGreen = nBlue = 0;
		if( nBri < 50 ) nRed = nGreen = nBlue = 255;
	}
	else
	{
		nHue = (nHue + 120) % 240;
		nLoop = 20;
		while( nLoop )
		{
			SfxHSBtoRGB(nHue, nSat, nBri, &nRed, &nGreen, &nBlue);
			nCalcLum = LUMINANCE(nRed,nGreen,nBlue);
			if( abs(nOrigLum - nCalcLum) >= nThreshold ) break;
			if( nOrigLum <= 50 )
			{
				nSat -= 5;
				if( nSat < 0 ) nSat += 5;
				nBri += 10; 
				if( nBri > 100 ) nBri = 100;
			}
			else
			{
				nSat += 5;
				if( nSat > 100 ) nSat = 100;
				nBri -= 5; 
				if( nBri < 10 ) nBri = 10;
			}
			nLoop--;
		}
	}
	return RGB(nRed,nGreen,nBlue);
}

//-------------------------------------------------------------------------//
// Retrieve a Luminance from RGB color                                     //
//-------------------------------------------------------------------------//
int SfxGetLuminance(COLORREF crRGB)
{
	return 	LUMINANCE(GetRValue(crRGB),GetGValue(crRGB),GetBValue(crRGB));
}

//macros
#define HSB(h,s,b) ((COLORREF)(((BYTE)(b)|((WORD)((BYTE)(s))<<8))|(((DWORD)(BYTE)(h))<<16)))
#define LUMINANCE(r,g,b) ((30*r+59*g+11*b)/255)

#define GetLValue(hsb)	 ((BYTE)(hsb))
#define GetSValue(hsb)	 ((BYTE)(((WORD)(hsb)) >> 8))
#define GetHValue(hsb)	 ((BYTE)((DWORD)(hsb)>>16))
#define	HUE_UNDEF	 0x000000FF


If you have some questions or new idea, please send me.



The Ghost in the Mind Machine
QuestionRe: Contrasting color? What's new Pin
murx9-Jul-15 8:06
murx9-Jul-15 8:06 
GeneralTOLERANCE Pin
Roger657-May-04 5:18
Roger657-May-04 5:18 
GeneralRe: TOLERANCE Pin
User 10455757-May-04 20:32
User 10455757-May-04 20:32 
GeneralRGB Color Cube Pin
Todd Smith5-May-04 8:43
Todd Smith5-May-04 8:43 
GeneralBlack and White / Gray Pin
Patje5-May-04 4:33
Patje5-May-04 4:33 
GeneralRe: Black and White / Gray Pin
User 10455755-May-04 5:38
User 10455755-May-04 5:38 
GeneralRe: Black and White / Gray Pin
Henry Jacobs5-May-04 10:43
Henry Jacobs5-May-04 10:43 
GeneralRe: Black and White / Gray Pin
Samuel Gonzalo11-Jun-04 0:13
Samuel Gonzalo11-Jun-04 0:13 
GeneralRe: Black and White / Gray Pin
User 104557513-Jul-04 22:43
User 104557513-Jul-04 22:43 
QuestionSimpler? Pin
Kippesoep5-May-04 4:28
Kippesoep5-May-04 4:28 
AnswerRe: Simpler? Pin
Patje5-May-04 4:34
Patje5-May-04 4:34 
GeneralRe: Simpler? Pin
Kippesoep5-May-04 9:48
Kippesoep5-May-04 9:48 
GeneralRe: Simpler? Pin
Patje6-May-04 4:43
Patje6-May-04 4:43 
AnswerRe: Simpler? Pin
User 10455755-May-04 5:24
User 10455755-May-04 5:24 
GeneralRe: Simpler? Pin
Kippesoep5-May-04 9:47
Kippesoep5-May-04 9:47 
GeneralRe: Simpler? Pin
User 10455756-May-04 4:14
User 10455756-May-04 4:14 
GeneralRe: Simpler? Pin
Kippesoep6-May-04 5:13
Kippesoep6-May-04 5:13 
GeneralRe: Simpler? Pin
User 10455757-May-04 1:24
User 10455757-May-04 1:24 
AnswerRe: Simpler? Pin
Steve Mayfield6-May-04 13:50
Steve Mayfield6-May-04 13:50 
GeneralRe: Simpler? Pin
Kippesoep6-May-04 21:02
Kippesoep6-May-04 21:02 
GeneralSome hints about RGB->HSL Pin
Kochise4-May-04 22:39
Kochise4-May-04 22:39 
GeneralRe: Some hints about RGB-&gt;HSL Pin
Paolo Messina5-May-04 3:13
professionalPaolo Messina5-May-04 3:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.