如何获取TMemo中显示的行数?

时间:2017-07-01 14:22:37

标签: delphi firemonkey

我需要获取TMemo中显示的行数(这包括由于WordWrap设置为true而被包装的行)。我需要这个来自动调整Tmemo的高度到它的内容。

line.count当然不关心包裹线,所以我无法使用它。奇怪的是TextPosToPos也不关心包裹线,所以我也不能使用它......

我在firemonkey和delphi Berlin下

3 个答案:

答案 0 :(得分:2)

在我了解ContentsBounds之后编辑。我的原始(和过时的)答案在修订版中仍然可见。

为什么需要显示的行数来调整TMemo的高度?这会将TMemo的大小调整为其内容:

Memo1.Height := Memo1.ContentBounds.Height + 5; // Small const to allow for rendering margins

还需要考虑自动换行。

答案 1 :(得分:1)

我不知道为什么使用ContentBounds“不是很理想”。我是这样做的:

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;

答案 2 :(得分:-1)

这是我用来计算firemonkey下TMemo(样式)的行数的粗略方法:

type
  _TStyledMemoProtectedAccess = class(TStyledMemo);

procedure TALStyledMemo.OnApplyStyleLookupImpl(sender: Tobject);
Var I, j, k, l: integer;
begin

  // TALStyledMemo
  //   TStyledMemo
  //      TLayout
  //         TActiveStyleObject
  //            TLayout
  //            TScrollBar
  //            TScrollBar
  //            TLayout
  //               TSmallScrollBar
  //               TSmallScrollBar
  //   TScrollContent
  for I := 0 to controls.Count - 1 do begin
    if (controls[i] is TStyledMemo) then begin // << TStyledMemo
      fStyledMemo := TStyledMemo(controls[i]);
    end;
  end;

end;

function TALStyledMemo.getLineHeight: Single;
begin
  if fStyledMemo <> nil then result := _TStyledMemoProtectedAccess(fStyledMemo).GetLineHeight
  else result := 0;
end;

function TALStyledMemo.getLineCount: integer;
var aLineHeight: Single;
begin
  aLineHeight := getLineHeight;
  if compareValue(aLineHeight, 0, Tepsilon.Position) > 0 then result := round(ContentBounds.Height / aLineHeight)
  else result := 0;
end;