How to paint 2 gradients together on a Canvas?

前端 未结 4 865
情深已故
情深已故 2021-02-08 11:16

Please look at this sample gradient image I did with a Paint program:

\"enter

It c

4条回答
  •  臣服心动
    2021-02-08 11:27

    Delphi 2005 and up:

    Use GradientFillCanvas from the GraphUtil unit:

    procedure TForm1.FormPaint(Sender: TObject);
    var
      R: TRect;
    begin
      SetRect(R, 0, 0, ClientWidth, ClientHeight div 2);
      GradientFillCanvas(Canvas, clWhite, $00056AFF, R, gdVertical);
      SetRect(R, 0, ClientHeight div 2, ClientWidth, ClientHeight); 
      GradientFillCanvas(Canvas, $000055FF, clWhite, R, gdVertical);
    end;
    

    Earlier Delphi versions:

    Use GradientFill from Msimg32.dll. Add the following code to a global utilities unit:

    type
      PTriVertex = ^TTriVertex;
      TTriVertex = record
        X, Y: DWORD;
        Red, Green, Blue, Alpha: WORD;
      end;
    
    function GradientFill(DC: HDC; Vertex: PTriVertex; NumVertex: ULONG;
      Mesh: Pointer; NumMesh, Mode: ULONG): BOOL; stdcall; overload;
      external msimg32 name 'GradientFill';
    
    function GradientFill(DC: HDC; const ARect: TRect; StartColor,
      EndColor: TColor; Vertical: Boolean): Boolean; overload;
    const
      Modes: array[Boolean] of ULONG = (GRADIENT_FILL_RECT_H, GRADIENT_FILL_RECT_V);
    var
      Vertices: array[0..1] of TTriVertex;
      GRect: TGradientRect;
    begin
      Vertices[0].X := ARect.Left;
      Vertices[0].Y := ARect.Top;
      Vertices[0].Red := GetRValue(ColorToRGB(StartColor)) shl 8;
      Vertices[0].Green := GetGValue(ColorToRGB(StartColor)) shl 8;
      Vertices[0].Blue := GetBValue(ColorToRGB(StartColor)) shl 8;
      Vertices[0].Alpha := 0;
      Vertices[1].X := ARect.Right;
      Vertices[1].Y := ARect.Bottom;
      Vertices[1].Red := GetRValue(ColorToRGB(EndColor)) shl 8;
      Vertices[1].Green := GetGValue(ColorToRGB(EndColor)) shl 8;
      Vertices[1].Blue := GetBValue(ColorToRGB(EndColor)) shl 8;
      Vertices[1].Alpha := 0;
      GRect.UpperLeft := 0;
      GRect.LowerRight := 1;
      Result := GradientFill(DC, @Vertices, 2, @GRect, 1, Modes[Vertical]);
    end;
    

    Now, the painting code becomes:

    procedure TForm1.FormPaint(Sender: TObject);
    var
      R: TRect;
    begin
      SetRect(R, 0, 0, ClientWidth, ClientHeight div 2);
      GradientFill(Canvas.Handle, R, clWhite, $00056AFF, True);
      SetRect(R, 0, ClientHeight div 2, ClientWidth, ClientHeight); 
      GradientFill(Canvas.Handle, R, $000055FF, clWhite, True);
    end;
    
    procedure TForm1.FormResize(Sender: TObject);
    begin
      Invalidate;
    end;
    

    GradientFill.png

提交回复
热议问题