问题描述
我编写了一个组件,用于绘制以 X、Y 为中心的图片。在运行时,组件通过 SetXY(X,Y: integer)
过程移动。
为了实现这一点,我计算了绘制例程中的 Left
和 Top
值并相应地设置它们。一切正常。
但是当我尝试在设计时进行初始定位时,我无法通过将其拖动到所需位置来定位该组件。
当我通过对象检查器设置 Left
或 Top
属性时,它可以工作。
procedure MyCustomComponent.SetTop(const Value: integer);
begin
if Top = (Value) then
exit;
inherited Top := Value;
if csDesigning in ComponentState then
FY := Value + FBmp.Width div 2;
Invalidate;
end;
procedure MyCustomComponent.SetLeft(const Value: integer);
begin
if Left = (Value) then
exit;
inherited Left := Value;
if csDesigning in ComponentState then
FX := Value + FBmp.Width div 2;
Invalidate;
end;
我怀疑在设计时将组件拖放到 Form 上时,它实际上并没有设置 Left
和 Top
公共属性,而是调用了一些其他函数来设置我从 (TGraphicControl
) 继承组件的底层控件的私有字段成员。
解决方法
正如 fpiette 和 Remy 所指出的,覆盖 SetBounds
成功了。在设计时通过拖放组件定位组件时,它不会单独设置公共 Left
和 Top
属性。而是调用 SetBounds
过程。
procedure MyComponent.SetBounds(ALeft,ATop,AWidth,AHeight: Integer);
begin
inherited;
if csDesigning in ComponentState then begin
FX := ALeft + FBmp.Width div 2;
FY := ATop + FBmp.Height div 2;
end;
end;
编辑:
经过测试,我发现要在运行时将组件正确放置在表单上,您还必须检查组件状态中的 csLoading
。
所以更完整的解决方案是这样的:
procedure MyComponent.SetBounds(ALeft,AHeight: Integer);
begin
inherited;
if (csDesigning in ComponentState) or (csLoading in ComponentState ) then begin
FX := ALeft + FBmp.Width div 2;
FY := ATop + FBmp.Height div 2;
end;
end;