2

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.

Kromster
  • 7,181
  • 7
  • 63
  • 111
Rahul Bajaj
  • 135
  • 2
  • 14
  • 1
    The label won't tell you this. You could infer it by making the label auto size and checking its height. Divide that height by the height of a single line, round to nearest, and hope for the best!! I expect if you have a lot of lines then at some point that will become inaccurate. If you want to be perfect, you need to handle the wrapping manually. – David Heffernan Nov 25 '15 at 10:08
  • I believe the number of lines will remain 1 at all times, its the painting or something that will make it appear as 2 lines. So there is no way to know this unless you handle the wrapping yourself somehow – GuidoG Nov 25 '15 at 14:48

2 Answers2

0

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;
Community
  • 1
  • 1
fantaghirocco
  • 4,761
  • 6
  • 38
  • 48
0
  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;
David K.
  • 39
  • 9