在 VCL 中,TLabel
使用 Win32 APIDrawText()
函数计算文本宽度,使用GetDC()
获取HDC
屏幕的 ,然后SelectObject()
将其当前选择Font
到HDC
. 您必须在自己的代码中执行相同的操作,例如:
// set Label1.AutoSize to False and Label1.Width to
// the max width your UI will accept the Label1 to be...
function WillFitInLabel(Label: TLabel; const S: String): Boolean;
var
R: TRect;
C: TCanvas;
DC: HDC;
begin
R := Rect(0, 0, Label.Width, 0);
C := TCanvas.Create;
try
DC := GetDC(0);
try
C.Handle := DC;
try
C.Font := Label1.Font;
Windows.DrawText(DC, PChar(S), Length(S), R, DT_SINGLELINE or DT_CALCRECT);
finally
C.Handle := 0;
end;
finally
ReleaseDC(0, DC);
end;
finally
C.Free;
end;
Result := (R.Width <= Label.Width);
end;
var
Names: String;
begin
Names := ...;
if WillFitInLabel(Label1, Names) then
Label1.Caption := Names
else
...
end;