Quando trabalhamos com cores é notável que há vários padrões para representa-las. No Delphi não é diferente, sendo que há uma classe específica denominada TColor.
Porém muitas vezes precisaremos da representação em outros padrões, como por exemplo, HTML e utilizar em automatizações de cadastros ou mesmo em integrações.
Legal mas como é possível fazer a conversão?
Bem, sem uma ajuda, algumas conversões não são muito intuitivas. Felizmente este post vai simplificar muito a conversão.
Vamos ao Exemplo 1
1
2
3
4
5
6
7
8
9
10
11
function ColorToHtml1(Color: TColor):string;var
COL:LongInt;begin
COL := ColorToRGB(Color);{ first convert TColor to Integer to remove the higher bits }{ erst TColor zu Integer, da die Unnötigen höheren Bit entfernt werden }
Result :='#'+IntToHex(COL and$FF,2)+IntToHex(COL shr8and$FF,2)+IntToHex(COL shr16and$FF,2);end;
function ColorToHtml1(Color: TColor): string;
var
COL: LongInt;
begin
COL := ColorToRGB(Color);
{ first convert TColor to Integer to remove the higher bits }
{ erst TColor zu Integer, da die Unnötigen höheren Bit entfernt werden }
Result := '#' + IntToHex(COL and $FF, 2) +
IntToHex(COL shr 8 and $FF, 2) +
IntToHex(COL shr 16 and $FF, 2);
end;
Neste exemplo a informação em TColor é convertida primeiro para RGB e Depois para hexadecimal e concatenado para resultar no padrão hexadecimal do HTML.
Parece difícil? Bem tem mais uma sugestão!
Vamos ao código do Exemplo 2
1
2
3
4
5
function ColorToHtml2(Clr: TColor):string;begin
Result :=IntToHex(clr,6);
Result :='#'+Copy(Result,5,2)+Copy(Result,3,2)+Copy(Result,1,2);end;
function ColorToHtml2(Clr: TColor): string;
begin
Result := IntToHex(clr, 6);
Result := '#' + Copy(Result, 5, 2) + Copy(Result, 3, 2) + Copy(Result, 1, 2);
end;
Neste exemplo é convertido para hexadecimal e depois formatado no padrão HTML.
Gostou? Mas e agora se precisar fazer a conversão ao contrário, é possivel?
Claro!, Vamos a um exemplo simples que vai lhe ajudar muito.
Exemplo Inverso, convertendo com HTML para TColor do Delphi
1
2
3
4
function HtmlToColor(Color:string): TColor;begin
Result := StringToColor('$'+Copy(Color,6,2)+Copy(Color,4,2)+Copy(Color,2,2));end;
function HtmlToColor(Color: string): TColor;
begin
Result := StringToColor('$' + Copy(Color, 6, 2) + Copy(Color, 4, 2) + Copy(Color, 2, 2));
end;
This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.
Strictly Necessary Cookies
Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.
If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.