Re: TForm with gradient colors

Posted by webmaster Guido on July 29, 2007

In Reply to Re: Delphi Form with gradient color posted by webmaster Guido on July 28, 2007

: : how can I set a gradient background for the form, going gradually from one color to another color?
: [...] put some component on the form, whose colors can be set to your liking [etc...]
: For example a ToolBar, because it has all the desired properties such as GradientStartColor [etc...]
I've tested this with Turbo Delphi, and the result looks quite convincing. I haven't figured out yet if this also works in other Delphi versions [etc...]

Well, here's the bad news: it doesn't work in Delphi 7 and older versions, because their Toolbar component didn't have gradient-color features.

But the good news is, that you can paint a rectangle on any Canvas with gradient colors with the API function GradientFill.

In the following code example, let's paint the entire form in gradient colors, say from light blue to white.
Firstly, create an event handler by double clicking on the OnPaint event in the Object Inspector.
Next, complete the source code as follows:

procedure TForm1.FormPaint(Sender: TObject);
  arTVX : array[0..1] of TRIVERTEX;
  arTVX[0].X      := 0;
  arTVX[0].Y      := 0;
  arTVX[0].Red    := $7800; 
  arTVX[0].Green  := $B900;
  arTVX[0].Blue   := $D900;
  arTVX[0].Alpha  := $0000;

  arTVX[1].X      := Width;
  arTVX[1].Y      := Height;
  arTVX[1].Red    := $FF00;
  arTVX[1].Green  := $FF00;
  arTVX[1].Blue   := $FF00;
  arTVX[1].Alpha  := $0000;

  GradRect.UpperLeft  := 0;
  GradRect.LowerRight := 1;

  GradientFill(Canvas.Handle, @arTVX, 2, @GradRect, 1, GRADIENT_FILL_RECT_H);

Likewise, create an event handler for the form's OnResize event and complete as follows:

procedure TForm1.FormResize(Sender: TObject);

Note that we set the starting and ending colors in arTVX[0] and in in arTVX[1].

The desired RGB values are set in the fields Red, Green and Blue, in a special format: not as simple byte values from 0 to 255, but left-shifted by 8 positions.
In human language, that is: multiplied by 256. Or, in semi-computer language: append 00 to the hexadecimal representations.
Thus, "pure red" is coded as $FF00 / $0000 / $0000. White is coded as $FF00 / $FF00 / $FF00, as seen in our source code example above.

Related articles


Follow Ups