Skip to content

Instantly share code, notes, and snippets.

Created March 15, 2013 20:46
Show Gist options
  • Save anonymous/5172991 to your computer and use it in GitHub Desktop.
Save anonymous/5172991 to your computer and use it in GitHub Desktop.
WPF Measure String
private static double GetStringWidth(string text, Control control)
{
Typeface typeface = new Typeface(control.FontFamily, control.FontStyle, control.FontWeight, control.FontStretch);
GlyphTypeface glyphTypeface;
if (!typeface.TryGetGlyphTypeface(out glyphTypeface))
throw new InvalidOperationException("No glyph typeface found");
double size = control.FontSize;
ushort[] glyphIndexes = new ushort[text.Length];
double[] advanceWidths = new double[text.Length];
double totalWidth = 0;
for (int n = 0; n < text.Length; n++)
{
ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];
glyphIndexes[n] = glyphIndex;
double width = glyphTypeface.AdvanceWidths[glyphIndex] * size;
advanceWidths[n] = width;
totalWidth += width;
}
return totalWidth;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment