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.
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.
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;
SpriteFont font = Content.Load<SpriteFont>("myFont");
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!"
{{
to get ["blue}}Hel"], ["green}}lo, "], ["yellow}}wor"], ["red}}ld!"]
.}}
to get a combination of color and text e.g. ["blue", "Hel"]
.