ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetScreenSize

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

Source

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

Author: Matthias Glauch

Submitted on: 8 sep. 2011

Language: C#

Type: System.String

Views: 5978