Mega Code Archive

 
Categories / Delphi / Graphic
 

How to Convert a HTML Hex Color to TColor

Title: How to Convert a HTML Hex Color to TColor Question: ive recently come across the need to do this convert, it seemed simple enough but i couldnt find any examples anywhere. Here is the code for how to do this conversion. Answer: say we have a variable: const BGCOLOR = '#003366'; and we want to assign this to the background color of a memo or any other TColor we can do this simply by calling the function and using the return value like so: procedure TForm1.Button1Click(Sender: TObject); begin Memo.Color := ConvertHtmlHexToTColor(BGCOLOR); end; I could have made the code in the CheckHexForHash function inline, but i intend to make a few more functions and procedures that will need it. Heres the full unit as it stands at the moment. copy and paste the whole thing or just the bits you need. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- unit colours; interface uses Windows, Sysutils, Graphics; function ConvertHtmlHexToTColor(Color: String):TColor ; function CheckHexForHash(col: string):string ; implementation //////////////////////////////////////////////////////////////////////////////// // ConvertHtmlHexToTColor // function ConvertHtmlHexToTColor(Color: String):TColor ; var rColor : TColor; begin Color := CheckHexForHash(Color); if (length(color) = 6) then begin {remember that TColor is bgr not rgb: so you need to switch then around} color := '$00' + copy(color,5,2) + copy(color,3,2) + copy(color,1,2); rColor := StrToInt(color); end; result := rColor; end; //////////////////////////////////////////////////////////////////////////////// // CheckHexForHash: // Simply checks the first character of a string for '#' and removes it if found function CheckHexForHash(col: string):string ; begin if col[1] = '#' then col := StringReplace(col,'#','',[rfReplaceAll]); result := col; end; end.