似乎有align
一个工作得很好的属性,但是可以对齐元素,因此如果面板上的所有元素都小于容器的大小,那么面板上的所有元素都将对齐到彼此底部的中心?类似于顶部中心中心的东西。
像这样的东西:
或者至少水平和垂直它们可以有 100%。
似乎有align
一个工作得很好的属性,但是可以对齐元素,因此如果面板上的所有元素都小于容器的大小,那么面板上的所有元素都将对齐到彼此底部的中心?类似于顶部中心中心的东西。
像这样的东西:
或者至少水平和垂直它们可以有 100%。
将元素放入它们自己的容器中,例如 a TPanel
or TFrame
,它是主容器的子容器。将子容器的Align
属性设置为alCustom
并使用父容器的OnAlignPosition
事件使子容器以自身为中心:
// Panel1 is the Parent container for the child panel...
procedure TMyForm.Panel1AlignPosition(Sender: TWinControl; Control: TControl;
var NewLeft, NewTop, NewWidth, NewHeight: Integer; var AlignRect: TRect;
AlignInfo: TAlignInfo);
begin
if Control = ChildPanel then
begin
NewLeft := AlignRect.Left + ((AlignRect.Width - Control.Width) div 2);
NewTop := AlignRect.Top + ((AlignRect.Height - Control.Height) div 2);
end;
end;
无需编写任何代码。只需以正确的方式放置面板和其他视觉对象,并设置视觉对象的属性,如下所示:
Align: alNone or alCustom
and
Anchors: none (akLeft=False, akTop=False, akRight=False, akBottom=False)
Than 和一个对象将停留在其相对的水平和垂直位置。如果将它放在容器的中间,它将保持居中。
仅将其居中设置为垂直设置
Align: alNone or alCustom
and
Anchors: akTop=True OR akBottom=True
仅将其居中设置为水平设置
Align: alNone or alCustom
and
Anchors: akLeft=True OR akRight=True
您可以使用这个小程序将控件居中
procedure CenterControl( AControl : TControl );
begin
if Assigned( AControl.Parent )
then
begin
// remove alignment
AControl.Align := alNone;
// remove the anchors
AControl.Anchors := [];
// center on parent
AControl.Left := ( AControl.Parent.ClientWidth - AControl.Width ) div 2;
AControl.Top := ( AControl.Parent.ClientHeight - AControl.Height ) div 2;
end
else
raise Exception.Create( 'Control needs a Parent!' );
end;
如果父级调整大小,只要您没有更改其大小,控件将始终居中。
在 RAD 10+ 中有一个控件 TRelativePanel,它具有 AlignVerticalCenterWithPanel 和 AlignHorisontalCenterWithPanel 救生选项(以及其他有用的功能)。
您还可以在中心放置不可见的线或点,并使用 TRelativePanel 提供的属性 Above/Below/等围绕它构建其他控件。值得一提的是,控制是根据顶级 Embarcadero 质量标准进行的(仅在设计模式下崩溃)。