我曾经为字符串编写了一个扩展方法来获取其屏幕大小,具体取决于字体系列,大小等.
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)