Calculate needed size for a TLabel

You can use the TCanvas.TextRect method, along with the tfCalcRect and tfWordBreak flags :

var
  lRect : TRect;
  lText : string;

begin
  lRect.Left := 0;
  lRect.Right := myWidth;
  lRect.Top := 0;
  lRect.Bottom := 0;
  
  lText := myLabel.Caption;

  myLabel.Canvas.Font := myLabel.Font;
  myLabel.Canvas.TextRect( 
            {var} lRect, //will be modified to fit the text dimensions
            {var} lText, //not modified, unless you use the "tfModifyingString" flag
            [tfCalcRect, tfWordBreak] //flags to say "compute text dimensions with line breaks"
          );
  ASSERT( lRect.Top = 0 ); //this shouldn't have moved
  myLabel.Height := lRect.Bottom;
end;

TCanvas.TextRect wraps a call to the DrawTextEx function from the Windows API.

The tfCalcRect and tfWordBreak flags are delphi wrappers for the values DT_CALCRECT and DT_WORDBREAK of the windows API. You can find detailed information about their effects in the DrawTextEx documentation on msdn


Use TextWidth and TextHeight.

See an example here: http://www.greatis.com/delphicb/tips/lib/fonts-widthheight.html

TextWidth will tell you how wide the text would be, and then you can divide that by the control width to see how many rows you need. The remainder of the division should be an additional row.


If you can align it alTop and keep AutoSize on then TLabel will auto adjust the height after settign the caption.


You can use one line of code for this:

label.width := label.canvas.textwidth(label.caption);

or you can set the label's autosize property to true in the object inspector.

Tags:

Delphi