SpriteFont

AdvancedProgrammer

The SpriteFont class is a convenient way to draw text. It works with the SpriteBatch class.

Note

You need to put all custom code in a Custom scene renderer to include it in the composition.

Load a spriteFont

After a font asset is compiled it can be loaded as a SpriteFont instance using the @'Xenko.Core.Serialization.Assets.ContentManager'. It contains all the options to display a text (bitmaps, kerning, line spacing etc).

Code: Load a SpriteFont

  1. var myFont = Content.Load<SpriteFont>("MyFont");

Write text on screen

Once the font is loaded, you can display any text with a SpriteBatch. The @'Xenko.Graphics.SpriteBatch.DrawString' method performs the draw. For more information about the SpriteBatch, see the SpriteBatch page.

Code: Write text

  1. // create the SpriteBatch
  2. var spriteBatch = new SpriteBatch(GraphicsDevice);
  3. // don't forget the begin
  4. spriteBatch.Begin(GraphicsContext);
  5. // draw the text "Helloworld!" in red from the center of the screen
  6. spriteBatch.DrawString(myFont, "Helloworld!", new Vector2(0.5, 0.5), Color.Red);
  7. // don't forget the end
  8. spriteBatch.End();

The various overloads let you specify the text's orientation, scale, depth, origin, etc. You can also apply some SpriteEffects to the text:

  • None
  • FlipHorizontally
  • FlipVertically
  • FlipBothCode: Advanced text drawing
  1. // draw the text "Hello world!" upside-down in red from the center of the screen
  2. spriteBatch.DrawString(myFont, "Hello world!", new Vector2(0.5, 0.5), Color.Red, 0, new Vector2(0, 0), new Vector2(1,1), SpriteEffects.FlipVertically, 0);

See also