forked from Rampastring/Rampastring.XNAUI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextParseReturnValue.cs
105 lines (82 loc) · 3.23 KB
/
TextParseReturnValue.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework.Graphics;
using System.Text;
namespace Rampastring.XNAUI;
public class TextParseReturnValue
{
public int LineCount;
public string Text;
public TextParseReturnValue(string text, int lineCount)
{
Text = text;
LineCount = lineCount;
}
public static TextParseReturnValue FixText(SpriteFont spriteFont, int width, string text)
{
string line = string.Empty;
int lineCount = 0;
string processedText = string.Empty;
string[] wordArray = text.Split(' ');
foreach (string word in wordArray)
{
if (spriteFont.MeasureString(line + word).Length() > width)
{
processedText = processedText + line + Environment.NewLine;
lineCount++;
line = string.Empty;
}
line = line + word + " ";
}
processedText = processedText + line;
return new TextParseReturnValue(processedText, lineCount);
}
public static List<string> GetFixedTextLines(SpriteFont spriteFont, int width, string text, bool splitWords = true, bool keepBlankLines = false)
{
if (string.IsNullOrEmpty(text))
return new List<string>(0);
var returnValue = new List<string>();
// Remove '\r' characters so Windows newlines aren't counted twice
string[] lineArray = text.Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.None);
foreach (string originalTextLine in lineArray)
{
if (keepBlankLines && originalTextLine == string.Empty)
returnValue.Add(string.Empty);
string line = string.Empty;
string[] wordArray = originalTextLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string word in wordArray)
{
if (spriteFont.MeasureString(line + word).X > width)
{
if (line.Length > 0)
{
returnValue.Add(line.Remove(line.Length - 1));
}
// Split individual words that are longer than the allowed width
if (splitWords && spriteFont.MeasureString(word).X > width)
{
var sb = new StringBuilder();
for (int i = 0; i < word.Length; i++)
{
if (spriteFont.MeasureString(sb.ToString() + word[i]).X > width)
{
returnValue.Add(sb.ToString());
sb.Clear();
}
sb.Append(word[i]);
}
if (sb.Length > 0)
line = sb.ToString() + " ";
continue;
}
line = word + " ";
continue;
}
line = line + word + " ";
}
if (!string.IsNullOrEmpty(line) && line.Length > 1)
returnValue.Add(line.TrimEnd());
}
return returnValue;
}
}