在给定尺寸,样式等的情况下,有没有办法找到固定宽度字体的字符宽度?

Mat*_*att 2 c# wpf fonts textbox

有没有办法在给定的大小,样式等给定的固定宽度字体中找到字符的宽度(字符的开头到下一个字符的开头之间的距离)(例如Courier New,Bold,大小16)?

基本上我需要确定每行n个字符的TextBox宽度应该是多少(Font只在运行时才知道,因此我不能简单地对数字进行硬编码).

找到角色宽度的最佳方法是什么?或者有更好的方法来确定TextBox的宽度?

Mat*_*asG 5

我曾经为字符串编写了一个扩展方法来获取其屏幕大小,具体取决于字体系列,大小等.

public static Size GetScreenSize(this string text, FontFamily fontFamily, double fontSize, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch)
{
    fontFamily = fontFamily ?? new TextBlock().FontFamily;
    fontSize = fontSize > 0 ? fontSize : new TextBlock().FontSize;
    var typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
    var ft = new FormattedText(text ?? string.Empty, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, typeface, fontSize, Brushes.Black);
    return new Size(ft.Width, ft.Height);
}
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

"Hello World".GetScreenSize(fontFamily, 12, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
Run Code Online (Sandbox Code Playgroud)

您还可以使用默认样式TextBlock:

"Hello World".GetScreenSize(null, 0, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
Run Code Online (Sandbox Code Playgroud)

您也可以查看extensionmethod.net获取相同的信息.

编辑:

如果你有一个固定宽度的字体,你可以使用任意字符计算宽度,如下所示:

double width = "X".GetScreenSize(fontFamily, 12, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal) * numbersOfCharacters;
Run Code Online (Sandbox Code Playgroud)