Avatar of mike_marquet
mike_marquet

asked on 

Get a correct text color from a back color !

How can I get a correct text color from a back color so that the text is also visible on a dark back color ?
C++

Avatar of undefined
Last Comment
Computer101
Avatar of MacroLand
MacroLand
Flag of United States of America image

Did you try to XOR your text color with the back color ?
Avatar of mike_marquet
mike_marquet

ASKER

If I do this, the text color becomes the same as the back color.

COLORREF clrText = RGB(0,0,0); // default text color is black
COLORREF clrBack = RGB(0,0,0); // background color is black

=> text color must becomes white

clrText = clrText ^ clrBack => black ?
Avatar of MacroLand
MacroLand
Flag of United States of America image

Even in a professional program if you draw white color line to a white background you wont notice it.

But if you want to see it black

clrText = !(clrText ^ clrBack)
Avatar of mike_marquet
mike_marquet

ASKER

It doens't works. The text color stays back on a dark background color.

But I have found a solution using the luminance value :

double GetLuminance(COLORREF clr)
 {
  return 0.3 * GetRValue(clr) + 0.59 * GetGValue(clr) + 0.11 * GetBValue(clr);
 }

COLORREF clrText = GetLuminance() < 120.0 ? RGB(255,255,255) : RGB(0,0,0);
Avatar of MacroLand
MacroLand
Flag of United States of America image

Sounds to be a good one but I am not sure if 120 will always work.
ASKER CERTIFIED SOLUTION
Avatar of Computer101
Computer101
Flag of United States of America image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
C++
C++

C++ is an intermediate-level general-purpose programming language, not to be confused with C or C#. It was developed as a set of extensions to the C programming language to improve type-safety and add support for automatic resource management, object-orientation, generic programming, and exception handling, among other features.

58K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo