Archive

Posts Tagged ‘string’

How to Convert TColor to a Hex String and Vice Versa

December 15th, 1999 m3Rlin No comments

Delphi uses TColor to represent colors but HTML requires a string name (139 colors have names in the web palette) or a hex number. Here’s the code to convert a TColor color value to hex a string and vise versa.
The functions use the Windows API GetRValue(), GetBValue(), GetGValue() and RGB() functions.

!Note: If your are going to use this in a unit that has a form remember that the colColor and sColor parameters must have different names than Color else the function will take the form’s color.

(* Returns a string representation of the colColor parameter in XXXXXX format,
** X being a hex digit.
*)
function TColorToHex(const colColor: TColor): string;
begin
  Result := IntToHex(GetRValue(colColor), 2) + { Red value }
    IntToHex(GetGValue(colColor), 2) +         { Green value }
    IntToHex(GetBValue(colColor), 2);          { Blue value }
end;

{ sColor should be in XXXXXX format, X being a hex digit }
function HexToTColor(const sColor: string): Cardinal;
begin
  Result := RGB(StrToInt('$' + Copy(sColor, 1, 2)), { Get red value }
    StrToInt('$' + Copy(sColor, 3, 2),              { Get green value }
    StrToInt('$' + Copy(sColor, 5, 2));             { Get blue value }
end;

How to Set the Length of a String

December 15th, 1999 m3Rlin No comments

The string length is automatically set but sometimes you want to change the length yourself. That’s because sometimes you have to have the same length of a string every time (when saving to binary files). You can always use the string[n] (ShortString) type but their maximum length is 256 characters.

!!Note: You CAN NOT set the length of string constants.

var
  sString: string;
...
  { This code sets the string length to 512 characters }
  SetLength(sString, 512);