Refactor text wrapping into WidgetUtils

This commit is contained in:
Paul Chote
2011-05-05 23:03:17 +12:00
parent f3a54a802a
commit c270f9ff4a
2 changed files with 56 additions and 49 deletions

View File

@@ -50,6 +50,7 @@ namespace OpenRA.Widgets
Color = other.Color;
Contrast = other.Contrast;
ContrastColor = other.ContrastColor;
WordWrap = other.WordWrap;
GetText = other.GetText;
GetBackground = other.GetBackground;
}
@@ -104,56 +105,8 @@ namespace OpenRA.Widgets
position += new int2(Bounds.Width - textSize.X,0);
if (WordWrap)
{
if (textSize.X > Bounds.Width)
{
string[] lines = text.Split('\n');
List<string> newLines = new List<string>();
int i = 0;
string line = lines[i++];
while (true) // TODO: WTF IS THIS SHIT?
{
newLines.Add(line);
int2 m = font.Measure(line);
int spaceIndex = 0, start = line.Length - 1;
if (m.X <= Bounds.Width)
{
if (i < lines.Length - 1)
{
line = lines[i++];
continue;
}
else
break;
}
text = WidgetUtils.WrapText(text, Bounds.Width, font);
while (m.X > Bounds.Width)
{
if (-1 == (spaceIndex = line.LastIndexOf(' ', start)))
break;
start = spaceIndex - 1;
m = font.Measure(line.Substring(0, spaceIndex));
}
if (spaceIndex != -1)
{
newLines.RemoveAt(newLines.Count - 1);
newLines.Add(line.Substring(0, spaceIndex));
line = line.Substring(spaceIndex + 1);
}
else if (i < lines.Length - 1)
{
line = lines[i++];
continue;
}
else
break;
}
text = string.Join("\n", newLines.ToArray());
}
}
if (Contrast)
font.DrawTextWithContrast(text, position, Color, ContrastColor, 2);
else

View File

@@ -12,6 +12,7 @@ using System;
using System.Drawing;
using System.Linq;
using OpenRA.Graphics;
using System.Collections.Generic;
namespace OpenRA.Widgets
{
@@ -140,6 +141,59 @@ namespace OpenRA.Widgets
else
return "{0:D2}:{1:D2}".F(minutes, seconds % 60);
}
public static string WrapText(string text, int width, SpriteFont font)
{
int2 textSize = font.Measure(text);
if (textSize.X > width)
{
string[] lines = text.Split('\n');
List<string> newLines = new List<string>();
int i = 0;
string line = lines[i++];
while (true)
{
newLines.Add(line);
int2 m = font.Measure(line);
int spaceIndex = 0, start = line.Length - 1;
if (m.X <= width)
{
if (i < lines.Length - 1)
{
line = lines[i++];
continue;
}
else
break;
}
while (m.X > width)
{
if (-1 == (spaceIndex = line.LastIndexOf(' ', start)))
break;
start = spaceIndex - 1;
m = font.Measure(line.Substring(0, spaceIndex));
}
if (spaceIndex != -1)
{
newLines.RemoveAt(newLines.Count - 1);
newLines.Add(line.Substring(0, spaceIndex));
line = line.Substring(spaceIndex + 1);
}
else if (i < lines.Length - 1)
{
line = lines[i++];
continue;
}
else
break;
}
return string.Join("\n", newLines.ToArray());
}
return text;
}
}
[Flags]