Delphi/Lazarus: Readable Font Color for arbitrary Background Color
Tip by Delphian | 02.11.2015 at 18:51
How to select a suitable color for a font, if the background can have an arbitrary color? Recently, I asked myself this question when I was programming my own color dialog.
In this dialog, I wanted to show the value of the color directly on the corresponding color and of course, the color value should always remain readable, no matter which background color is selected. I have coded the following function for this purpose.
function GetContrastColorBlackOrWhite(const AColor: TColor): TColor; var R, G, B: single; begin R := GetRValue(AColor) * 0.25; G := GetGValue(AColor) * 0.625; B := GetBValue(AColor) * 0.125; if (R + G + B) > 128 then begin result := clBlack; end else begin result := clWhite; end; end;
You can pass an arbitrary color to this function and the function will give you either black or white as return value, depending on which color is better fitting to the passed color as background or foreground color.
In the example above, we are setting the background color of an edit field to black and we are calling the function in order to find a suitable color for the text. The function will return white white as color of choice.
Edit1.Color := clBlack; Edit1.Font.Color := GetContrastColorBlackOrWhite(clBlack);
The trick of the function is, that the function is building the sum of all color values with a specific factor in order to compare the result with 128. Of course, you can also change this threshold to a higher or lower value, depending on where you would like to have the jump between black and white.
About the Author
The author has not added a profile short description yet.
Tutorial | 1 Comment
Tutorial | 0 Comments
Tutorial | 0 Comments
Question | 3 Answers
Tip | 1 Comment
Question | 1 Answer
Info | 0 Comments
Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.
Ask your own question or write your own article on askingbox.com. That’s how it’s done.