How can I use the DrawString
function and send it a rectangle
(to set the alignment)? If the text is longer from the rectangle's width then the line will continue until the end of the line?
(not multi line case!!)
Asked
Active
Viewed 446 times
0
-
What do you want to happen if the text is longer than the width of the rectangle? Truncate the text? Wrap it to another line? – gunr2171 Nov 03 '13 at 14:13
-
Are you trying to make sure you're filling an entire area with the text? Do you want to overwrite what's beneath? Then I suggest you do a `FillRectangle` first, to clear the text background. – PMF Nov 03 '13 at 14:14
-
You may need to `MeasureString` first and adjust the rectangle accordingly so that the text fits. – Wagner DosAnjos Nov 03 '13 at 14:16
-
@user2949943 You mean, if the test is longer than a certain width, it will simply stop? Instead of extending? – Cyral Nov 03 '13 at 16:29
1 Answers
1
I created an extension method to remove any text outside of the horizontal destination region. (I assume this is what you meant) It adds an option ellipsis to the text (...
) to let users know the text continues.
public static void DrawStringTrim(this SpriteBatch spriteBatch, SpriteFont font, Rectangle rect, string text, Color color)
{
// Characters to append to end of text, can be removed.
string ellipsis = "...";
// Get the width of the text string.
int size = (int)Math.Ceiling(font.MeasureString(text).X);
// Is text longer than the destination region? If not, simply draw it
if (size > rect.Width)
{
// Account for the length of the "..." (ellipsis) string.
int es = string.IsNullOrWhiteSpace(ellipsis) ? 0 : (int)Math.Ceiling(font.MeasureString(ellipsis).X);
for (int i = text.Length - 1; i > 0; i--)
{
int c = 1;
// Remove two letters if the preceding character is a space.
if (char.IsWhiteSpace(text[i - 1]))
{
c = 2;
i--;
}
// Chop off the tail of the string and re-measure the width.
text = text.Remove(i, c);
size = (int)Math.Ceiling(font.MeasureString(text).X);
// Text is short enough?
if (size + es <= rect.Width)
break;
}
// Append the ellipsis to the truncated string.
text += ellipsis;
}
// Draw the text
spriteBatch.DrawString(font, text, new Vector2(rect.X, rect.Y), color);
}
You can then draw the string you want with spriteBatch.DrawStringTrim(font, new Rectangle(Width, Height), "Some really really long text!", Color.White);

Cyral
- 13,999
- 6
- 50
- 90