【问题标题】:How to automatically adjust my variables when my component size changes?当我的组件尺寸发生变化时如何自动调整我的变量?
【发布时间】:2018-09-11 21:17:48
【问题描述】:

在我的组件中,每次更改 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 在加载设计器的值时不会被触发。

【问题讨论】:

  • 在构造函数中设置位图大小。
  • 我试过了。它不工作。
  • 虽然可能是错误的,但我通常会在Paint 处理程序的开头调整BMP 大小。当然,先检查它是否已经不是要求的值,如果它已经正确,不要费心去分配。
  • @jerry 在类外检查没有意义,因为位图类已经检查了
  • @David 感谢您指出这一点,我认为这可能是不必要的(我目前无法访问我的 IDE)。不过很好奇,我怀疑在 Paint 处理程序中这样做是错误的吗?

标签: delphi resize components delphi-2009


【解决方案1】:

我找到了解决办法!

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

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

【讨论】:

    猜你喜欢
    • 2022-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-06
    相关资源
    最近更新 更多