WPF相当于TextRenderer
我已经使用TextRenderer
来测量字符串的长度,因此适当地调整控件的大小。 在WPF中是否有等价物,或者我可以简单地使用TextRendered.MeasureString
?
谢谢Gishu,
阅读你的链接我想出了以下两个为我做的工作:
/// /// Get the required height and width of the specified text. Uses FortammedText /// public static Size MeasureTextSize(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) { FormattedText ft = new FormattedText(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(fontFamily, fontStyle, fontWeight, fontStretch), fontSize, Brushes.Black); return new Size(ft.Width, ft.Height); } /// /// Get the required height and width of the specified text. Uses Glyph's /// public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize) { Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch); GlyphTypeface glyphTypeface; if(!typeface.TryGetGlyphTypeface(out glyphTypeface)) { return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize); } double totalWidth = 0; double height = 0; for (int n = 0; n < text.Length; n++) { ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]]; double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize; double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex]*fontSize; if(glyphHeight > height) { height = glyphHeight; } totalWidth += width; } return new Size(totalWidth, height); }
看看FormattedText类
如果您需要更精细的控制,那么您需要下降到GlyphTypeface类型的AdvanceWidths成员。 在这里找到类似的讨论 ,其代码片段看起来可能有用。
更新 :看起来这可能与WPF中的测量文本重复.OP请确认。