This xna code snip allows you to draw text, with the option of having that text
word wrapped to the specified rectangle or you can specify text alignment info
like weather or not the text should be drawn anchored to the bottom right of the
rectangle or top right etc.
public static void DrawString(SpriteBatch sb,
SpriteFont
fnt, string
text, Rectangle r,
Color col, TextAlignment align, bool
performWordWrap, Vector2 offsett, out Rectangle
textBounds)
{
// check if there is text
to draw
textBounds = r;
if (text == null) return;
if (text == string.Empty) return;
StringCollection lines = new StringCollection();
lines.AddRange(text.Split(new string[] { "\\n"}, StringSplitOptions.RemoveEmptyEntries));
// calc the size of the
rect for all the text
Rectangle tmprect = ProcessLines(fnt,
r, performWordWrap, lines);
// setup the position where drawing will
start
Vector2 pos = new Vector2(r.X, r.Y);
int aStyle =
0;
switch
(align)
{
case TextAlignment.Bottom:
pos.Y
= r.Bottom - tmprect.Height;
aStyle = 1;
break;
case TextAlignment.BottomLeft:
pos.Y
= r.Bottom - tmprect.Height;
aStyle = 0;
break;
case TextAlignment.BottomRight:
pos.Y
= r.Bottom - tmprect.Height;
aStyle = 2;
break;
case TextAlignment.Left:
pos.Y
= r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 0;
break;
case TextAlignment.Middle:
pos.Y
= r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 1;
break;
case TextAlignment.Right:
pos.Y
= r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 2;
break;
case TextAlignment.Top:
aStyle
= 1;
break;
case TextAlignment.TopLeft:
aStyle
= 0;
break;
case TextAlignment.TopRight:
aStyle
= 2;
break;
}
// draw text
for (int idx = 0; idx < lines.Count;
idx++)
{
string txt =
lines[idx];
Vector2 size =
fnt.MeasureString(txt);
switch (aStyle)
{
case 0:
pos.X = r.X;
break;
case 1:
pos.X = r.X +
((r.Width / 2) - (size.X / 2));
break;
case 2:
pos.X = r.Right - size.X;
break;
}
// draw the line of
text
sb.DrawString(fnt, txt, pos + offsett, col);
pos.Y +=
fnt.LineSpacing;
}
textBounds =
tmprect;
}
internal static Rectangle
ProcessLines(SpriteFont fnt, Rectangle r,
bool
performWordWrap, StringCollection lines)
{
// llop through each line
in the collection
Rectangle bounds = r;
&nb