delphi - 如何以编程方式确定 TMemo 中一行文本的高度?

标签 delphi tmemo

我有一个 TMemo,我希望它总是足够高以显示它包含的行数。不幸的是,我不太清楚如何计算。我不能以 .Font.Size 为基础属性,因为这会因 DPI 而异。而且我不能使用TCanvas.TextHeight因为 TMemo 似乎没有 Canvas 。

有人知道如何正确执行此操作吗?

最佳答案

我看到一个问题,我认为 TMemo 上的所有行的高度都相等,但有些可能是空的......

因此,当它们在 TMemo 上的高度不是零时,获取空的高度将给出零。

所以解决方案可能会做类似 Memo.Lines.Count*LineHeight

请注意,Canvas.TextHeight 可能无法获取 Lineheight,因为 Canvas.TextHeight 将为文本提供或多或少的最小高度的精确高度......我的意思是它不会为文本“ABC”提供与“ABCp”相同的高度, ETC...

我建议(如果不想调用 Windows API)使用 Font.Height,但如果它是负数,则不测量每行的内部前导......

所以我建议做接下来的步骤(经过测试):

  • 在 OnCreate 事件或您想要的任何地方为 Memo.Font.Height 分配一个正值,这样 TMemo 的 lineheight 将是您分配的值
  • 现在可以通过 Memo.Lines.Count*LineHeight 直接获得总高度,因为您已为 Memo.Font.Height 分配了一个正值(请记住,这会使 Memo.Font.Size 为负)

  • 我个人在 TForm OnCreate 事件上执行此操作(以确保它只执行一次),只是为了确保视觉字体大小不会更改并且 MyMemo.Font.Height 包括每行的内部前导:
    MyMemo.Font.Height:=Abs(MyMemo.Font.Size*MyMemo.Font.PixelsPerInch div Screen.PixelsPerInch);
    

    确保前面只执行一次,否则文本大小会越来越大,就像你运行它的次数一样...这是因为并非总是 MyMemo.Font.PixelsPerInch 等于 Screen.PixelsPerInch...在我的情况下,它们分别是 80 和 96。

    然后,当我需要知道行高时,我只需使用:
    Abs(MyMemo.Font.Height*Screen.PixelsPerInch div 72)
    

    这给出了一个 TMemo 行的精确高度,因为所有行都具有相同的高度,所以总高度将是:
    MyMemo.Lines.Count*Abs(MyMemo.Font.Height*Screen.PixelsPerInch div 72)
    

    因此,为了使 TMemo 高度与其包含的文本一样大,我这样做(阅读每一行的注释,它们非常重要):
    MyMemo.Font.Height:=Abs(MyMemo.Font.Size*MyMemo.Font.PixelsPerInch div Screen.PixelsPerInch); // I do this on the Tform OnCreate event, to ensure only done once
    MyMemo.Height:=1+MyMemo.Lines.Count*Abs(MyMemo.Font.Height*Screen.PixelsPerInch div 72); // I do this anywhere after adding the text and/or after editing it
    

    我你不想玩 Screen.PixelsPerInch 你可以这样做(阅读每一行的注释,它们非常重要):
    MyMemo.Font.Height:=Abs(MyMemo.Font.Height); // This may make text size to visually change, that was why i use the corrector by using MyMemo.Font.PixelsPerInch and Screen.PixelsPerInch
    MyMemo.Height:=1+MyMemo.Lines.Count*Abs(MyMemo.Font.Height*MyMemo.Font.PixelsPerInch div 72);
    

    希望这可以帮助任何人。

    关于delphi - 如何以编程方式确定 TMemo 中一行文本的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6804929/

    相关文章:

    delphi - 计算 Delphi TMemo 中每行的最大字符数

    delphi - 如何检测应用程序中的表单是否被破坏?

    delphi - 如何将自定义格式的剪贴板数据粘贴到 TMemo 中?

    delphi - 寻找delphi的通信框架

    delphi - 为什么 Synopse 连字代码给出的结果与 TeX 的结果不同?

    delphi - Delphi 中的 TMemo 滚动

    string - 删除备忘录上的特定行

    delphi - 如何使 StringGrid 的列适合网格的宽度?

    德尔福 2007 : save only the breakpoint options in the DSK file?