GetScreenSize

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);
}
Example:
FontFamily fontFamily; // = ...
// gets the screen size of 'Hello World'
"Hello World".GetScreenSize(fontFamily, 12, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);
// this one uses the default font family and the default font size
"Hello World".GetScreenSize(null, 0, FontStyles.Normal, FontWeights.Normal, FontStretches.Normal);

Description

Calculates the visual size of a string if it would be displayed on the screen, i.e. as the text of a TextBlock.

Details

Double click on the code to select all.

 

;