在VCL,TLabel
使用Win32 API DrawText()
函數來計算文本寬度,使用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;
您使用的是VCL還是FMX? –