如何在组件大小更改时自动调整变量?

时间:2018-04-02 16:28:17

标签: delphi resize components delphi-2009

在我的组件中,我需要在WidthHeight每次更改时但在绘制组件之前调整一些变量。我尝试覆盖Resize方法并更新那里的变量,但它并不总是有效。请参阅下面的代码。如果我在运行时创建组件,那么每个组件都可以。但是,如果我在设计时将组件放在Form上,更改其大小并运行程序,我的组件将以默认大小绘制,因为新大小未在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

1 个答案:

答案 0 :(得分:1)

我找到了解决方案!

而是重写Resize我必须覆盖SetBounds,因为Resize是从SetBounds调用的,但是在加载组件的属性时却没有。

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