如何测量 WPF 中的 multi-line 文本?

How to measure multi-line text in WPF?

标题说明了一切...我需要知道如何在 WPF 中测量 multi-line 文本。我真的不敢相信这个问题还没有在这里问过。

我找到了测量 WPF 中单行文本的解决方案 (WPF equivalent to TextRenderer), or multi-line text in Windows Forms (C# – Measure String Width & Height (in pixels) Including Multi-line Text),但没有找到 multi-line WPF 中的文本。我无法使用 Windows Forms DLL,因为我需要在非 UI 项目中测量字符串,其中不欢迎 UI DLL。

为了进一步澄清,我需要的是一种方法,例如 Graphics.MeasureString 方法,我可以将设置的宽度传递给该方法,它将 return 呈现字符串所需的高度(以像素为单位)在 UI... 中可以在不使用 UI 相关 DLL 的情况下使用。

您可以创建一个 FormattedText 实例并设置其 MaxTextWidth 属性,使文本换行。然后要么从 Bounds 获取它的几何形状,或者只从 Extent 属性:

获取它的高度
var testString = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor";

var formattedText = new FormattedText(
    testString,
    CultureInfo.InvariantCulture,
    FlowDirection.LeftToRight,
    new Typeface("Segoe UI"),
    20,
    Brushes.Black);

formattedText.MaxTextWidth = 200;

var bounds = formattedText.BuildGeometry(new Point(0, 0)).Bounds;
var height = formattedText.Extent;

但不确定为什么 heightbounds.Height 不完全相等。