如何获得 Run 或 Paragraph 的高度

问题描述 投票:0回答:2

我在

Run
中找到了
Paragraph
FlowDocument
,现在我需要知道它的HEIGHT

while (navigator.CompareTo(flowDocViewer.Document.ContentEnd) < 0)
  {
      TextPointerContext context = navigator.GetPointerContext(LogicalDirection.Backward);
      Run run = navigator.Parent as Run;
      // I need to get HEIGHT of Run in pixels somehow

事实上可以吗?

enter image description here

谢谢!

c# .net wpf height flowdocument
2个回答
7
投票

我正在使用的一个小功能。输入是一个包含 Section 的字符串。您可以轻松渲染其他块元素,例如段落。

你也可以省略 Parse 方法的第二个参数。

诀窍不是测量段落,而是测量包含 RichTextBox 的 ViewBox。这是实际呈现 Flowdocument 所必需的。 ViewBox 动态获取 rtb 的大小。也许你甚至可以在没有 ViewBox 的情况下做到这一点。我花了一些时间来解决这个问题,它对我有用。

注意

Width
RichTextBox
设置为
double.MaxValue
。这意味着当您要测量单个段落时,它必须很长或者所有内容都在一行中。所以这只有在您知道输出设备的宽度时才有意义。因为这是一个 FlowDocument,所以没有宽度,它会流动 ;) 我用它来对我知道纸张大小的 FlowDocument 进行分页。

返回的高度是设备独立单位。

private double GetHeaderFooterHeight(string headerFooter)
        {

            var section = (Section)XamlReader.Parse(headerFooter, _pd.ParserContext);
            var flowDoc = new FlowDocument();
            flowDoc.Blocks.Add(section);

            var richtextbox = new RichTextBox { Width = double.MaxValue, Document = flowDoc };
            var viewbox = new Viewbox { Child = richtextbox };

            viewbox.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
            viewbox.Arrange(new Rect(viewbox.DesiredSize));

            var size = new Size() { Height = viewbox.ActualHeight, Width = viewbox.ActualWidth };

            return size.Height;
        }

0
投票

这对我有用:

Rect start = run.ElementStart.GetCharacterRect(LogicalDirection.Forward);
Rect end = run.ElementEnd.GetCharacterRect(LogicalDirection.Forward);

// Do math with start and end

在我的例子中,我的

Run
都以换行符结尾,所以我可以测量从
start.Top
end.Top
,但你可能需要检查
end.Bottom

© www.soinside.com 2019 - 2024. All rights reserved.