tags:

views:

153

answers:

4

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?

+1  A: 

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

Freek
+5  A: 

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.

Chris Thornton
+4  A: 

Hi,

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.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

LeGEC
+1  A: 

you can use one line code for this

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

or you can use label autosize property to true at object inspector.

sabri.arslan