How to get the HEIGHT of the Run or Paragraph

喜夏-厌秋 提交于 2020-01-23 01:34:21

问题


I found the Run or Paragraph in FlowDocument and now I need to know the HEIGHT of it.

i.e.

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

Is it possible to do in fact?

Thank you!


回答1:


A little function i am using. The input is a string containing a Section. You can easily render other blockelements like Paragraph.

You also can omit the second parameter of the Parse method.

The trick is not to measure the Paragraph, but the ViewBox which contains a RichTextBox. This is needed to actually render the Flowdocument. The ViewBox dynamically gets the size of the rtb. Maybe you even can do this without the ViewBox. I spent some time to figure this out and it works for me.

Note that Width of the RichTextBox is set to double.MaxValue. This means when you want to measure a single paragraph it has to be very long or everything is in one line. So this only makes sense when you know the Width of your output device. As this is a FlowDocument there is no Width, it flows ;) I use this to paginate a FlowDocument where i know the paper size.

The returned Height is device independent units.

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;
        }


来源:https://stackoverflow.com/questions/15978206/how-to-get-the-height-of-the-run-or-paragraph

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!