如何在wpf中计算FormattedText或GlyphRun的'Size'?

Cod*_*987 6 wpf formatting glyph

在WPF4,我怎么可以计算'Size'FormattedText或者GlyphRun一个drawingvisual.

我在画布上使用drawingvisual.当我更改文本大小或文本时,会发生更改但实际宽度和高度相同或不会更新.

Using dc As DrawingContext = drawingvisual.RenderOpen                    

                Dim ft As New FormattedText(...)

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

                dc.Close()

End Using
Run Code Online (Sandbox Code Playgroud)

Ed *_*tes 6

一旦初始化了FormattedText,它的Width和Height成员等于其给定参数的实际渲染大小.实际上,更改参数会立即更新它们,例如:

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;
Run Code Online (Sandbox Code Playgroud)

编辑GlyphRun:当您创建GlyphRun时,您已经为每个字符提供了预先宽度,因此您可以为宽度添加宽度.要获得高度,请使用GlyphTypeface.Baseline*FontSize


Mar*_*rio 5

顺便说一句:我注意到使用 DrawingContext.DrawGlyphRun 与 DrawingContext.DrawFormattedText 相比,性能提高了大约 10 倍。

GlyphRun 没有很好的文档记录,但是一旦您阅读了本文,您应该能够理解它是如何工作的。