Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate needed size for a TLabel

Tags:

delphi

Ok, here's the problem. I have a label component in a panel. The label is aligned as alClient and has wordwrap enabled. The text can vary from one line to several lines. I would like to re-size the height of the the panel (and the label) to fit all the text.

How do I get the necessary height of a label when I know the text and the width of the panel?

like image 781
Tom Avatar asked Apr 27 '10 13:04

Tom


3 Answers

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

like image 152
LeGEC Avatar answered Nov 13 '22 20:11

LeGEC


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.

like image 11
Chris Thornton Avatar answered Nov 13 '22 21:11

Chris Thornton


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.

like image 3
sabri.arslan Avatar answered Nov 13 '22 20:11

sabri.arslan