delphi transparent background component

2019-09-01 06:27发布

问题:

Quick question in regard to Delphi XE.

I'm trying to make a customized circle-shape component that has transparent background, so that when added on a form, the component can overlap other components. I've tried Brush.Style:=bsTransparent; or ellipse() and more on... but still couldn't find a way to make the edge area transparent.

Is there anyway I can make the edge area of the component transparent without using other lib or api?

回答1:

Well here's a quick answer, that should get you going.

type
  TEllipticPanel = class(Vcl.ExtCtrls.TPanel)
    procedure CreateWnd; override;
    procedure Paint; override;
    procedure Resize; override;
    procedure RecreateHRGN;
 end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    panl: TEllipticPanel;
  public
    { Public declarations }
  end;

implementation

procedure TForm1.FormCreate(Sender: TObject);
begin
  panl := TEllipticPanel.Create(self);
  panl.Left := 10;
  panl.Top := 10;
  panl.Width := 100;
  panl.Height := 50;
  panl.ParentBackground := False;
  panl.ParentColor := False;
  panl.Color := clYellow;
  panl.Parent := self;
end;

{ TEllipticPanel }

procedure TEllipticPanel.RecreateHRGN;
var
  hr: hRgn;
begin
  inherited;
  hr := CreateEllipticRgn(0,0,Width,Height);
  SetWindowRgn(Handle, hr, True);
end;

procedure TEllipticPanel.CreateWnd;
begin
  inherited;
  RecreateHRGN;
end;

procedure TEllipticPanel.Paint;
begin
  inherited;
  Canvas.Brush.Style := bsClear;
  Canvas.Pen.Style := TPenStyle(psSolid);
  Canvas.Pen.Width := 1;
  Canvas.Pen.Color := clGray;
  Canvas.Ellipse(1,1,Width-2,Height-2);
end;

procedure TEllipticPanel.Resize;
begin
  inherited;
  RecreateHRGN;
end;

The key is the Windows CreateEllipticRgn and the GDI SetWindowRgn functions.

For more information about windows regions see Regions.