Search code examples
delphifiremonkey

How to get the number of displayed lines in TMemo?


I need to get the number of displayed lines in TMemo (this include the lines that was wrapped because WordWrap is set to true). I need this to auto adjust the height of the Tmemo to it's content.

lines.count of course don't care about wrapped lines so i can't use it. strangely TextPosToPos also don't care about wrapped lines so i can't use it too ...

I m under firemonkey and delphi Berlin


Solution

  • I don't know why using ContentBounds is "not really ideal". Here's how I do it:

    uses
      FMX.TextLayout, FMX.Graphics;
    
    function MeasureTextHeight(const AFont: TFont; const AText: string): Single;
    var
      LLayout: TTextLayout;
    begin
      LLayout := TTextLayoutManager.DefaultTextLayout.Create;
      try
        LLayout.BeginUpdate;
        try
          LLayout.WordWrap := False;
          LLayout.Font.Assign(AFont);
          LLayout.Text := AText;
        finally
          LLayout.EndUpdate;
        end;
        Result := LLayout.TextHeight;
      finally
        LLayout.Free;
      end;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      LTextHeight: Single;
      LLines: Integer;
    begin
      LTextHeight := MeasureTextHeight(Memo1.TextSettings.Font, Memo1.Text);
      LLines := Round(Memo1.ContentBounds.Height / LTextHeight);
    end;