xnaspritefont

Substitute missing characters with "?" character


Is there an easy way to make default XNA method SpriteBatch.DrawString substitute characters that are not in spritefont with ? sign? I could go with an extension method, but I'm not sure how to implement it, as there is no way to know if a character is not in the spritefont beforehand.


Solution

  • This functionality is built-in. Open the .spritefont file for your font and scroll down to here:

    <!--
    If you uncomment this line, the default character will be substituted if you draw
    or measure text that contains characters which were not included in the font.
    -->
    <!-- <DefaultCharacter>*</DefaultCharacter> -->
    

    Uncomment that line and replace the character with the one you want, like so:

    <DefaultCharacter>?</DefaultCharacter>
    

    You can also achieve the same effect by modifying the SpriteFont.DefaultCharacter property at runtime.

    If you need it, you can get a list of the available characters in a font through the SpriteFont.Characters property.