uses .... LCLIntf, LCLType;
// calculate exact size of needed space for a control on screen
function TextToRect(const AText: String; const AFont: TFont): TRect;
var
bmp: TBitmap;
R: TRect;
begin
bmp := TBitmap.Create;
try
bmp.SetSize(1, 1);
bmp.Canvas.Font.Assign(AFont);
R := Rect(0, 0, 0, 0);
DrawText(bmp.Canvas.Handle, PChar(AText), Length(AText), R, DT_CALCRECT or DT_SINGLELINE);
Result := R;
finally
bmp.Free;
end;
end;
{ TForm1 }
procedure TForm1.Button1Click(Sender: TObject);
var
r: TRect;
begin
r := TextToRect(Panel1.Caption, Panel1.Font);
// r has now the exact size, so you should add some space on your own, like for border...
Panel1.Width := r.Width;
Panel1.Height := r.Height;
end;