I have a rectangle and a string and sometimes the string is too long for the rectangle, then I just want to draw the characters of the string that are in the rectangle. Every character that exceeds the border of the rectangle should not be drawn. But I don't know how to split up the long string into characters.
I want to do almost the same thing as described in this question: How can I split a long string so that it matches with a given rectangle?
But this time, the result should look like this:
string Playernickname = "Best_playerrrindaworrrrrld!!!";
//if the string is too long, then just draw the part that is in the rectangle, for example:
Playernickname = "Best_playerrrindaworrr";
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.DrawString(Font, Playernickname, new Vector2(200, 300), Microsoft.Xna.Framework.Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0f);
spriteBatch.End();
base.Draw(gameTime);
}
How can I split up a string into characters and only drawing the part of the string that is in the given rectangle?
UPDATE: I found out how to split a string into characters: https://social.msdn.microsoft.com/Forums/en-US/9b4e50dd-1136-42c8-af61-bbab96c5795d/split-a-word-to-characters?forum=csharplanguage
My code:
string Playernickname = "Best_playerrrindaworrrrrld!!!";
string[] Newword;
Newword = Splitchar(Playernickname, 200, Font).ToArray();
public static IEnumerable<string> Splitchar(string text, double rectangleWidth, SpriteFont font)
{
char[] chars = Encoding.Unicode.GetChars(Encoding.Unicode.GetBytes(text));
string buffer = string.Empty;
foreach (var character in chars)
{
var newBuffer = buffer + character.ToString();
if (character == chars[0])
newBuffer = character.ToString();
else
newBuffer = buffer + character.ToString();
Vector2 FontMeasurements = font.MeasureString(newBuffer);
if (FontMeasurements.X >= rectangleWidth)
{
yield return buffer;
buffer = character.ToString();
}
else
{
buffer = newBuffer;
}
}
yield return buffer;
}
//Drawing:
//This only draws the characters of the string that are in the rectangle.
spriteBatch.DrawString(Font, Newword[0], new Vector2(200, 300), Microsoft.Xna.Framework.Color.White, 0, Vector2.Zero, 1f, SpriteEffects.None, 0f);