Rahul Bajaj
Rahul Bajaj

Reputation: 135

Find number of lines in label with fixed length and word wrap property true

I have a label with fixed length and word wrap property set to true. At run time that label has two lines e.g.:

test := 'quick brown fox jumps over the lazy dog';

On Label this text displayed as two lines

quick brown fox jumps
over the lazy dog

I want to know number of lines at run time:

#13#10 does not work.

Upvotes: 2

Views: 3234

Answers (2)

David K.
David K.

Reputation: 39

  Function NumberOfLines(MyLabel: TLabel): Integer;
  var
    TempLabel: TLabel;
    Pint1: Integer;
  Begin
    TempLabel := TLabel.Create(Self);
    TempLabel.Caption := MyLabel.Caption;
    TempLabel.WordWrap := True;
    TempLabel.AutoSize := True;
    TempLabel.Width := MyLabel.Width;
    TempLabel.Font := MyLabel.Font;
    PInt1 := TempLabel.Height;
    TempLabel.Caption := '';
    TempLabel.WordWrap := False;
    TempLabel.AutoSize := True;
    Result := PInt1 div TempLabel.Height;
    TempLabel.Free;
  End;

Upvotes: 0

fantaghirocco
fantaghirocco

Reputation: 4868

The DrawText function can be used for this purpose.

The rest of the procedure doesn't differ so much from what David Heffernan proposes in his comment.

The key here is to adopt the flags DT_WORDBREAK to automatically break the lines and the DT_EDITCONTROL to mimic the caption's text behaviour.

function TForm1.getNumberOfLinesInCaption(ALabel: TLabel): Integer;
var
  r: TRect;
  h: Integer;
begin
  h := ALabel.Canvas.TextHeight(ALabel.Caption);
  if h = 0 then
    Exit(0);//empty caption

  if not ALabel.WordWrap then
    Exit(1);//WordWrap = False

  FillChar(r, SizeOf(TRect), 0);
  r.Width := ALabel.Width;
  r.Height := ALabel.Height;

  if 0 = DrawText(ALabel.Canvas.Handle, ALabel.Caption, Length(ALabel.Caption), r, DT_EDITCONTROL or DT_WORDBREAK or DT_CALCRECT) then
    Exit(-1);//function call has failed

  Result := r.Height div h;
  //Assert(r.Height mod h = 0);
end;

Upvotes: 0

Related Questions