Advertisement
FrayxRulez

Untitled

May 2nd, 2015
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. public List<string> WrapText(string text, int maxLineWidth)
  2. {
  3. string[] split = text.Split(' ');
  4. List<string> words = new List<string>(split);
  5. List<string> results = new List<string>();
  6. StringBuilder sb = new StringBuilder();
  7. float lineWidth = 0f;
  8. float spaceWidth = MeasureString(" ").Width;
  9.  
  10. for (int i = 0; i < words.Count; i++)
  11. {
  12. string word = words[i];
  13. float size = MeasureString(word).Width;
  14.  
  15. if (size > maxLineWidth)
  16. {
  17. words.Remove(word);
  18. foreach (var result in WrapWord(word, maxLineWidth).Reverse())
  19. {
  20. word = words[i];
  21. }
  22. word = words[i];
  23.  
  24. if (lineWidth + size < maxLineWidth)
  25. {
  26. sb.Append(word + " ");
  27. lineWidth += size + spaceWidth;
  28. }
  29. else
  30. {
  31. results.Add(sb.ToString());
  32. sb.Clear();
  33. sb.Append(word + " ");
  34. lineWidth = size + spaceWidth;
  35. }
  36. }
  37. }
  38.  
  39. return results;
  40. }
  41.  
  42. public IEnumerable<string> WrapWord(string word, int maxLineWidth)
  43. {
  44. for (int i = 0; i < word.Length; i++)
  45. {
  46. var sub = word.Substring(0, i);
  47. if (MeasureString(sub).Width < maxLineWidth)
  48. {
  49. yield return sub;
  50.  
  51. var end = word.Substring(i);
  52. if (MeasureString(end).Width < maxLineWidth)
  53. {
  54. yield return end;
  55. }
  56. else
  57. {
  58. foreach (var result in WrapWord(end, maxLineWidth))
  59. {
  60. yield return result;
  61. }
  62. }
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement