如何在我的组件大小发生变化时自动调整我的变量?

How to automatically adjust my variables when my component size changes?

在我的组件中,每次更改 WidthHeight 但在绘制组件之前,我都需要调整一些变量。我尝试覆盖 Resize 方法并在那里更新变量,但它并不总是有效。请参阅下面的代码。如果我在 运行 时间创建组件,一切都很好。但是,如果我在设计时将组件放在窗体上,更改其大小和 运行 程序,我的组件将以默认大小绘制,因为新大小不会像在 Resize 方法中那样更新。当我保存项目、关闭它并重新打开它时也会发生这种情况。

unit OwnGauge;

interface

uses
   Windows, SysUtils, Classes, Graphics, OwnGraphics, Controls, StdCtrls;

type
   TOwnGauge = class(TGraphicControl)
   private
     PaintBmp: TBitmap;
   protected
     procedure Paint; override;
     procedure Resize; override;
   public
     constructor Create(AOwner: TComponent); override;
     destructor  Destroy; override;
   end;

procedure Register;

implementation

procedure Register;
begin
 RegisterComponents('OwnMisc', [TOwnGauge]);
end;

constructor TOwnGauge.Create(AOwner: TComponent);
begin
 PaintBmp:= nil;
 inherited Create(AOwner);
 PaintBmp:= TBitmap.Create;
 PaintBmp.PixelFormat:= pf24bit;
 Width:= 200;
 Height:= 24;
end;

destructor TOwnGauge.Destroy;
begin
 inherited Destroy;
 PaintBmp.Free;
end;

procedure TOwnGauge.Paint;
begin
 with PaintBmp do begin
  Canvas.Brush.Color:= clRed;
  Canvas.Brush.Style:= bsSolid;
  Canvas.FillRect(ClientRect);
 end;
 BitBlt(Canvas.Handle, 0, 0, Width, Height, PaintBmp.Canvas.Handle, 0, 0, SRCCOPY);
end;

procedure TOwnGauge.Resize;
begin
 PaintBmp.SetSize(Width,Height);
 inherited;
end;

end.

编辑:

我做了进一步的研究,我发现在 WM_SIZE 消息的 TWinControl.WMSize 处理程序中是以下代码:

if not (csLoading in ComponentState) then Resize;

所以现在很明显当加载来自设计器的值时不会触发Resize

我找到了解决方案!

而不是覆盖 Resize 我必须覆盖 SetBounds,因为 Resize 是从 SetBounds 调用的,而不是在加载组件的属性时调用的。

procedure TOwnGauge.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
begin
 inherited;
 PaintBmp.SetSize(Width,Height);
end;