gpt4 book ai didi

c# - WPF 相当于 TextRenderer

转载 作者:可可西里 更新时间:2023-11-01 07:53:22 28 4
gpt4 key购买 nike

我已经使用 TextRenderer 来测量字符串的长度,因此可以适本地调整控件的大小。 WPF 中是否有等效项,或者我可以简单地使用 TextRendered.MeasureString

最佳答案

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

关于c# - WPF 相当于 TextRenderer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/824281/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com