1
\$\begingroup\$

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

enter image description here

How do I do this?

Thanks.

\$\endgroup\$
2
  • \$\begingroup\$ 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. \$\endgroup\$ Jun 15 '15 at 13:38
  • \$\begingroup\$ I thought I may need more SpriteFont files, but I don't. Edited \$\endgroup\$ Jun 15 '15 at 19:16
2
\$\begingroup\$

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!"

  • 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.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.