how to calculate 'Size' of FormattedText or GlyphRun in wpf?
Asked Answered
R

2

6

In WPF4, how can i calculate the 'Size' of FormattedText or GlyphRun for a drawingvisual.

I'm using drawingvisual in a canvas. When i change text size or text, changes occur but Actual Width and Height are same or don't get updated.

Using dc As DrawingContext = drawingvisual.RenderOpen                    

                Dim ft As New FormattedText(...)

                dc.DrawText(ft, New Point(0, 0))

                dc.Close()

End Using
Remise answered 16/7, 2011 at 12:0 Comment(0)
O
6

Once you've initialized the FormattedText, it has Width and Height members that are equal to its actual rendered size given its parameters. In fact, changing parameters updates them immediately, e,g,:

FormattedText ft = new FormattedText(cellString, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, fontFace, fontSize, fontBrush);
ft.Trimming = TextTrimming.CharacterEllipsis;
double originalHeight = ft.Height;
double width = ft.Width;
ft.MaxTextWidth = bCellRect.Width;    // Set the width to get a new height
double height = ft.Height;

Edit for GlyphRun: When you created your GlyphRun you already gave it the advance widths for each character, so you add those for the width. To get the height, use the GlyphTypeface.Baseline * FontSize

Okra answered 19/7, 2011 at 18:49 Comment(1)
When you created your GlyphRun you already gave it the advance widths for each character, so you add those for the width. To get the height, use the GlyphTypeface.Baseline * FontSize.Okra
B
5

Just as a side note: I've notice around 10x performance increase when using DrawingContext.DrawGlyphRun vs DrawingContext.DrawFormattedText.

GlyphRun is not well-documented, but once you read this article you should be able to understand how it works.

Banger answered 31/3, 2013 at 4:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.