Saturday, September 12, 2009

Need lighter or darker Color?

Simple functions to get lighter or darker value of a TColor a.K.a. Integer
(* darker color of thisColor by thePercent value *)
function DarkerColor(thisColor: TColor; thePercent: Byte): TColor;
var
  (* a TColor is made out of Red, Green and blue *)
  cRed,
  cGreen,
  cBlue: Byte;
begin
  (* get them individually *)
  cRed := GetRValue(thisColor);
  cGreen := GetGValue(thisColor);
  cBlue := GetBValue(thisColor);
  (* make them darker thePercent *)
  (* we need a byte value but the "/" operator
     returns a float value so we use Round function
     because type mismatch *)
  cRed := Round(cRed * thePercent / 100);
  cGreen := Round(cGreen * thePercent / 100);
  cBlue := Round(cBlue * thePercent / 100);
  (* return them as TColor *)
  Result := RGB(cRed, cGreen, cBlue);
end;

(* lighter color of thisColor by thePercent value *)
function LighterColor(thisColor: TColor; thePercent: Byte): TColor;
var
  cRed,
  cGreen,
  cBlue: Byte;
begin
  cRed := GetRValue(thisColor);
  cGreen := GetGValue(thisColor);
  cBlue := GetBValue(thisColor);
  (* a byte's range is from 0 to 255
     so Red, Green and Blue can have
     a value between 0 and 255 *)
  cRed :=
    Round(cRed * thePercent / 100) +
    Round(255 - thePercent / 100 * 255);
  cGreen :=
    Round(cGreen * thePercent / 100) +
    Round(255 - thePercent / 100 * 255);
  cBlue :=
    Round(cBlue * thePercent / 100) +
    Round(255 - thePercent / 100 * 255);
  Result := RGB(cRed, cGreen, cBlue);
end;

Usage
 aColor := DarkerColor(clRed, 15{percent});
 aColor := LighterColor(clBlack, 80{percent});

No comments:

Post a Comment

Blogroll(General programming and Delphi feeds)