Guest User

Untitled

a guest
Jun 19th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. /// <summary>
  2. /// Get the required height and width of the specified text. Uses FortammedText
  3. /// </summary>
  4. public static Size MeasureTextSize(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize)
  5. {
  6. FormattedText ft = new FormattedText(text,
  7. CultureInfo.CurrentCulture,
  8. FlowDirection.LeftToRight,
  9. new Typeface(fontFamily, fontStyle, fontWeight, fontStretch),
  10. fontSize,
  11. Brushes.Black);
  12. return new Size(ft.Width, ft.Height);
  13. }
  14.  
  15. /// <summary>
  16. /// Get the required height and width of the specified text. Uses Glyph's
  17. /// </summary>
  18. public static Size MeasureText(string text, FontFamily fontFamily, FontStyle fontStyle, FontWeight fontWeight, FontStretch fontStretch, double fontSize)
  19. {
  20. Typeface typeface = new Typeface(fontFamily, fontStyle, fontWeight, fontStretch);
  21. GlyphTypeface glyphTypeface;
  22.  
  23. if(!typeface.TryGetGlyphTypeface(out glyphTypeface))
  24. {
  25. return MeasureTextSize(text, fontFamily, fontStyle, fontWeight, fontStretch, fontSize);
  26. }
  27.  
  28. double totalWidth = 0;
  29. double height = 0;
  30.  
  31. for (int n = 0; n < text.Length; n++)
  32. {
  33. ushort glyphIndex = glyphTypeface.CharacterToGlyphMap[text[n]];
  34.  
  35. double width = glyphTypeface.AdvanceWidths[glyphIndex] * fontSize;
  36.  
  37. double glyphHeight = glyphTypeface.AdvanceHeights[glyphIndex]*fontSize;
  38.  
  39. if(glyphHeight > height)
  40. {
  41. height = glyphHeight;
  42. }
  43.  
  44. totalWidth += width;
  45. }
  46.  
  47. return new Size(totalWidth, height);
  48. }
Add Comment
Please, Sign In to add comment