Created
March 15, 2013 20:46
-
-
Save anonymous/5172991 to your computer and use it in GitHub Desktop.
WPF Measure String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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