# Word in different color in middle of string XNA

Is it possible to use different font colors for the same string, for example, when buying a weapon in CoD AW Exo Zombies:

How do I do this?

Thanks.

• Do you really want a different font, or only a different color like your example? Those are very different requirements, because you can draw one spritefont in any color at any time. Jun 15 '15 at 13:38
• I thought I may need more SpriteFont files, but I don't. Edited Jun 15 '15 at 19:16

You can simply render the pieces of colored text individually, specifying any color you want for each piece. In order to get the positioning correct, you can use the SpriteFont.MeasureString() method.

string[] stringPieces = { "Hel", "lo, ", "wor", "ld!" };
Color[] colors = { Color.Blue, Color.Green, Color.Yellow, Color.Red };

Vector2 startPosition = new Vector2(100, 100);
Vector2 offset = Vector2.Zero;

spriteBatch.Begin();

//Loop through each piece of the string,
//drawing each with a different color,
//and moving the offset forward by its measured length
for( int x = 0; x < stringPieces.Length; x++)
{
spriteBatch.DrawString(font, stringPieces[x], startPosition + offset, colors[x]);
offset.X += font.MeasureString(stringPieces[x]).X;
}

spriteBatch.End();


Code based on BTownTKD's GameDev.net post.

If you're going to do this often, I would recommend writing a basic parser to make using this easier.

Example syntax: "{{blue}}Hel{{green}}lo, {{yellow}}wor{{red}}ld!"

• Split on {{ to get ["blue}}Hel"], ["green}}lo, "], ["yellow}}wor"], ["red}}ld!"].
• Loop through each result and split on }} to get a combination of color and text e.g. ["blue", "Hel"].
• Render string "Hel" using Color.Blue. Continue.