这是用于对齐一些常见控件的代码...我不知道它是否覆盖了所有情况,但到目前为止,我尝试过的都完美运行。它适用于当前的Windows版本,但谁知道在未来版本中,当他们改变控件绘制方式时会发生什么。
TControlWithFont = class (TControl)
public
property Font;
end;
procedure FontBaselineAlign(Control, FixedControl: TControl);
var DC: HDC;
SaveFont: HFont;
CtrlBL, FixBL, BV: Integer;
CtrlTM, FixTM: TTextMetric;
function GetControlBaseLine(Ctrl: Tcontrol; const TM: TTextMetric; out BL: Integer): Boolean;
begin
Result:= False; BL:= -1;
if Ctrl is TLabel then with Ctrl as TLabel do begin
if Layout = tlTop then BL:= TM.tmAscent
else if Layout = tlBottom then BL:= Height - TM.tmDescent
else BL:= ((Height - TM.tmHeight) div 2 + TM.tmAscent);
Result:= True;
end
else if Ctrl is TEdit then with Ctrl as TEdit do begin
BL:= TM.tmAscent;
if BorderStyle = bsSingle then
Inc(BL, GetSystemMetrics(SM_CYEDGE)+1);
Result:= True;
end
else if (Ctrl is TSpinEdit) or (Ctrl is TComboBox) then begin
BL:= TM.tmAscent + GetSystemMetrics(SM_CYEDGE)+1;
Result:= True;
end
else if (Ctrl is TComboBoxEx) then begin
BL:= TM.tmAscent + GetSystemMetrics(SM_CYEDGE)+3;
Result:= True;
end
else if (Ctrl is TCheckBox) or (Ctrl is TRadioButton) then begin
BL:= ((Ctrl.Height - TM.tmHeight) div 2) + TM.tmAscent;
Result:= True;
end
else if (Ctrl is TColorBox) then begin
BL:= Round((Ctrl.Height - TM.tmHeight) / 2) + TM.tmAscent;
Result:= True;
end
else if (Ctrl is TPanel) then with Ctrl as TPanel do begin
BV:= BorderWidth;
if BevelInner <> bvNone then Inc(BV, BevelWidth);
if BevelOuter <> bvNone then Inc(BV, BevelWidth);
if BorderStyle = bsSingle then Inc(BV, GetSystemMetrics(SM_CYEDGE));
if VerticalAlignment = taAlignTop then begin
if (BevelKind <> bkNone) and (beTop in BevelEdges) then Inc(BV, GetSystemMetrics(SM_CYEDGE));
BL:= BV + TM.tmAscent;
end
else if VerticalAlignment = taAlignBottom then begin
if (BevelKind <> bkNone) and (beBottom in BevelEdges) then Inc(BV, GetSystemMetrics(SM_CYEDGE));
BL:= Height - TM.tmDescent - BV;
end
else BL:= ((Height - TM.tmHeight) div 2 + TM.tmAscent);
Result:= True;
end;
end;
begin
DC:= GetDC(0);
try
SaveFont:= SelectObject(DC, TControlWithFont(Control).Font.Handle);
GetTextMetrics(DC, CtrlTM);
SelectObject(DC, TControlWithFont(FixedControl).Font.Handle);
GetTextMetrics(DC, FixTM);
SelectObject(DC, SaveFont);
finally
ReleaseDC(0, DC);
end;
if GetControlBaseLine(Control, CtrlTM, CtrlBL) and
GetControlBaseLine(FixedControl, FixTM, FixBL) then
Control.Top:= FixedControl.Top + (FixBL - CtrlBL);
end;
TLabel
源代码。 - Andreas RejbrandTEdit
,我在源代码中找到了高度是如何计算的,但我找不到文本绘制的坐标。TCustomEdit
没有 Paint 方法,我不明白是谁绘制它的。 - Marus GradinaruTEdit
仅仅是操作系统(=Microsoft Windows)EDIT控件的一个包装器。因此,TEdit
VCL控件只是请求Windows创建其EDIT控件之一。这就是为什么TEdit
看起来与其他Win32应用程序中的编辑框完全相同,但与(有缺陷的)FMX编辑控件不同的原因。 - Andreas Rejbrand