Mega Code Archive

 
Categories / Delphi / Graphic
 

Calculate a contrasting text color to a background

//If the user can change the background color of a component, //make sure that the caption/text is displayed in a contrasting color. unit Unit1; interface uses Windows, SysUtils, Graphics, Controls, Forms, StdCtrls, Buttons, ComCtrls, Classes; type TForm1 = class(TForm) Edit1: TEdit; BitBtn1: TBitBtn; procedure BitBtn1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} function ContrastColor(clBackground: TColor): TColor; begin with TRGBQuad(clBackground) do if (rgbRed * 0.3) + (rgbGreen * 0.59) + (rgbBlue * 0.11) > 127.5 then Result:= clBlack else Result:= clWhite; end; //To test: procedure TForm1.BitBtn1Click(Sender: TObject); begin Edit1.Color:= Random(255) shl 16 + Random(255) shl 8 + Random(255); Edit1.Font.Color:= ContrastColor(Edit1.Color); end; end.