Delphi Programming

Colors in Delphi

2,918pages on
this wiki
Add New Page
Add New Page Talk0

In Delphi, colours are generally represented by a TColor, a hexadecimal number in 4 bytes. The internal format of TColor can have five formats:

  1. $00bbggrr -- Create using the RGB function
  2. $010000nn -- Create using the PaletteIndex function
  3. $02bbggrr -- Create using the PaletteRGB function
  4. $800000nn -- Defined in Graphics.PAS using Windows constants COLOR_SCOLLBAR, etc. These negative values must be passed to the ColorToRGB function to have R, G and B components defined.
  5. $FFFFFFFF -- If you create a TBitmap and do not define its height and width, the Pixels value will be -1 ($FFFFFFFF) and may cause range-check errors.

You can use the following functions for simplified color use (RGB as in HTML, instead of BGR that TColor uses).

by Zarko GajicEdit

Here are two simple functions to convert color values from TColor to Hex (HTML) and vice versa:

function TColorToHex(Color : TColor) : string;
   Result :=
     IntToHex(GetRValue(Color), 2) +
     IntToHex(GetGValue(Color), 2) +
     IntToHex(GetBValue(Color), 2) ;

// 2013-04-05: Replace GetRValue(Colour) with GetRValue(ColorToRGB(Color))
// This eliminates possible "range check error" messages with the above function
// New function ~ W.O.
function TColorToHex(Color : TColor) : string;
   Result :=
     IntToHex(GetRValue(ColorToRGB(Color)), 2) +
     IntToHex(GetGValue(ColorToRGB(Color)), 2) +
     IntToHex(GetBValue(ColorToRGB(Color)), 2) ;

function HexToTColor(sColor : string) : TColor;
   Result :=
       StrToInt('$'+Copy(sColor, 1, 2)),
       StrToInt('$'+Copy(sColor, 3, 2)),
       StrToInt('$'+Copy(sColor, 5, 2))
     ) ;

Original article can be found here.

by Dan StrandbergEdit

function ColorToRGBstring(Color: TColor): string;
  R,G,B : Integer; 
  R := Color and $ff; 
  G := (Color and $ff00) shr 8; 
  B := (Color and $ff0000) shr 16; 
  result := 'red:' + inttostr(r) + ' green:' + inttostr(g) + ' blue:' + inttostr(b); 

by Dmitri PapichevEdit

Working with separate colors:

   Windows, Graphics;

function Pale (AColor: TColor): TColor;
   R, G, B: byte;
   {strip away palette information from TColor data}
   AColor := ColorToRGB (Color);

   {extract color components}
   R := GetRValue (AColor); {red}
   G := GetGValue (AColor); {green}
   B := GetBValue (AColor); {blue}

   {apply some changes to color components}
   R := R + (255 - R) div 2;
   G := G + (255 - G) div 2;
   B := B + (255 - B) div 2;

   {convert separate colors back to TColor}
   Result := RGB (R, G, B);
end; {--Pale--}

See AlsoEdit

Code Snippets
DatabasesFiles and I/OForms/WindowsGraphicsNetworkingMath and AlgorithmsMiscellaneousMultimediaSystemVCL

Also on Fandom

Random Wiki