ในการแสดงข้อความต่างๆนี้เราจะใช้ เมธอด DrawString ของคลาส SpriteBatch
ซึ่งก่อนที่จะแสดงนี้เราต้องสร้าง SpriteFont ก่อน ให้ไปที่ folder content คลิกขวาเลือก Add->New Item จากนั้นให้เลือก Sprite Font
แล้วให้ตั้งชื่อด้วยในตัวอย่างนี้ตังชื่อว่า ArialFont.spritefont ดังรูป
จากนั้นคลิกที่ปุ่ม Add
หลังจากนั้นจะมีหน้า xml เกิดขึ้นมาในหน้านี้เราสามารถกำหนดรายละเอียดต่างๆเกี่ยวกับ font ได้เช่น ขนาด ฯ
ในการเรียกใช้งาน font นั้นสิ่งแรกเราจะต้องสร้างคลาส SpriteFont ขึ้นมาก่อนดังนี้
SpriteFont font;
และในเมธอด LoadContent ก็เขียนคำสั่งดังนี้
string str;
spriteBatch.Begin();
str = "Hello World";
spriteBatch.DrawString(font, str, new Vector2(50, 100), Color.Cornsilk);
spriteBatch.End();
ผลลัพธ์ ดังรูป

ตัวอย่างโค้ด Game1.cs
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
namespace WindowsGame4
{
public class Game1 : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
public Game1()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
base.Initialize();
}
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>("ArialFont");
}
protected override void UnloadContent()
{
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
string str;
spriteBatch.Begin();
str = "This is an Arial Font";
spriteBatch.DrawString(font, str, new Vector2(50, 100), Color.Cornsilk);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
[With great power comes great responsibility]