Mick
Mick

Reputation: 13485

Why does TPanel's color property display the wrong color when using a hex color value?

I am using Delphi 2010 and if I create a new VCL application, drop a TPanel on the form and set its "color" property to "clInactiveCaptionText" it shows the correct color.

Correct color:

enter image description here

However, if I enter the hex value for this color ($00434E54 --- R 67,G 78,B 84) it shows up incorrectly. I should note that the result is the same whether I enable runtime themes or not.

Wrong color:

enter image description here

Any idea on why it won't correctly show this color when specifying its hex value?

Upvotes: 7

Views: 2940

Answers (5)

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

With this simple function you can make easier:

Panel1.Color := HexToColor ('16a086');

Upvotes: 0

peiman F.
peiman F.

Reputation: 1658

Actually Tcolor is RGBA color format and also $FF000000 is the alpha channel so:

  • To get red chanel you can get $000000FF
  • To get green chanel you can get $0000FF00
  • To get bluechanel you can get $00FF0000
  • To get alpha chanel chanel you can get $FF000000

And easily you can convert the tcolor value to rgb by :

IntToHex(ColorPanel1.Color,1) 

this also work in cross platform FMX delphi apps.

Upvotes: 0

Deltics
Deltics

Reputation: 23046

As others have indicated, the RGB values are stored internally as BGR (i.e. TColor value, or what Windows calls a COLORREF), that's why when you specify a custom color code you obtain a different color.

To maintain your sanity when specifying colors in RGB form you can use the RGB() function from the Windows unit; this accepts parameters in the "natural"/intuitive RGB order (as byte values) and yields an appropriate TColor / COLORREF value:

  MyPanel.Color := RGB(67, 78, 84);

or if hex is easier:

  MyPanel.Color := RGB($43, $4E, $54);

Upvotes: 17

RRUZ
RRUZ

Reputation: 136431

This is because you are setting a TColor value in a RGB format you must use BGR instead.

Upvotes: 8

Marjan Venema
Marjan Venema

Reputation: 19356

RGB color values are actually specified as BGR.

So if you want:

  • red you need to specify $000000FF
  • green you need to specify $0000FF00
  • blue you need to specify $00FF0000

Upvotes: 19

Related Questions