C# WPF相当于TextRenderer
我使用了C# WPF相当于TextRenderer,c#,.net,wpf,C#,.net,Wpf,我使用了textrender来测量字符串的长度,从而适当地调整控件的大小。WPF中是否有等效项,或者我可以简单地使用TextRendered.MeasureString?查看 如果需要更细粒度的控制,则需要下降到GlyphTypeType类型的成员。在此处找到一个,其中包含一个代码段,该代码段看起来可能有效 更新:看起来这可能是..的副本。。OP请确认。谢谢Gishu 在阅读您的链接时,我想到了以下两种方法,这两种方法都适合我: /// <summary> /// G
textrender
来测量字符串的长度,从而适当地调整控件的大小。WPF中是否有等效项,或者我可以简单地使用TextRendered.MeasureString
?查看
如果需要更细粒度的控制,则需要下降到GlyphTypeType类型的成员。在此处找到一个,其中包含一个代码段,该代码段看起来可能有效
更新:看起来这可能是..的副本。。OP请确认。谢谢Gishu
在阅读您的链接时,我想到了以下两种方法,这两种方法都适合我:
/// <summary>
/// Get the required height and width of the specified text. Uses FortammedText
/// </summary>
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);
}
/// <summary>
/// Get the required height and width of the specified text. Uses Glyph's
/// </summary>
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);
}
//
///获取指定文本所需的高度和宽度。使用FortammedText
///
公共静态大小度量ExtSize(字符串文本、FontFamily FontFamily、FontStyle FontStyle、FontWeight FontWeight、FontStretch FontStretch、double fontSize)
{
FormattedText ft=新的FormattedText(文本,
CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
新字体(fontFamily、fontStyle、fontWeight、fontStretch),
字体大小,
刷子(黑色);
返回新尺寸(英尺宽、英尺高);
}
///
///获取指定文本所需的高度和宽度。使用Glyph的
///
公共静态大小度量文本(字符串文本、FontFamily FontFamily、FontStyle FontStyle、FontWeight FontWeight、FontStretch FontStretch、双fontSize)
{
字体字体=新字体(fontFamily、fontStyle、fontWeight、fontStretch);
字形字体字形字体;
如果(!typeface.TryGetGlyphTypeface(out glyphTypeface))
{
返回MeasureTextSize(文本、fontFamily、fontStyle、fontWeight、fontStretch、fontSize);
}
双总宽度=0;
双倍高度=0;
for(int n=0;n高度)
{
高度=高度;
}
总宽度+=宽度;
}
返回新尺寸(总宽度、高度);
}