Re: String to TColor

From: A man (uce_at_ftc.gov)
Date: 11/26/03


Date: Wed, 26 Nov 2003 11:38:08 -0500

Here are some useful color routines, including Tcolor to string and
string to TColor.

- Get separate R, G, and B values (Unit Windows)
Function GetBValue(rgb: DWORD): Byte;
Function GetGValue(rgb: DWORD): Byte;
Function GetRValue(rgb: DWORD): Byte;
VAR Color: Integer;
...
Color := ColorToRGB(clAqua);
ShowMessage(IntToStr(GetRValue(Color)) + ' ' +
            IntToStr(GetGValue(Color)) + ' ' +
            IntToStr(GetBValue(Color)));

- String To Color
Function StringToColor(Const S: String): TColor;

- Color to string (unit Graphics)

Function ColorToString(Color: TColor): String;
Returns something like '$0029a3ff'

- Color to HTML color format (Red and Blue reversed):

type
  TForm1 = class(TForm)
    ColorDialog1: TColorDialog;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    function HTMLColorValue(AColor:TColor):String;
  public
    { Public declarations }
  end;

{...}

procedure TForm1.Button1Click(Sender: TObject);

var
  tmpColor : TColor;
begin
  { execute our ColorDialog }
  if ColorDialog1.Execute then
  begin
    { get our selected color }
    tmpColor := ColorDialog1.Color
    { convert and display our selected color }
    ShowMessage(HTMLColorValue(tmpColor));
  end;
end;

function TForm1.HTMLColorValue(AColor:TColor):String;
var
  Red, Blue, Green : Integer;
begin
  { get red intensity }
  Red := GetRValue(AColor);

  { get blue intensity }
  Blue := GetBValue(AColor);

  { get green intensity }
  Green := GetGValue(AColor);

  { convert our color to HTML }
  Result := Format('#%2.2x%2.2x%2.2x', [Red,Green,Blue]);
end;

{...}

- RGB to Color
Function RGB(r, g, b: Byte): COLORREF;
BEGIN
  Result := (r OR (g SHL 8) OR (b SHL 16))
END;

-- 
"Tis better to be thought a fool than to open your mouth and remove all 
doubt."