FPS Drawable Game Component
From XNAWiki
A simple game component for rendering the 'frames per second' of the game.
public class FPSDisplay : DrawableGameComponent
{
private SpriteBatch spriteBatch;
private SpriteFont videoFont;
private float elapsedTime;
private float totalFrames;
private float fps;
private string fontName;
private Color textColor = Color.Red;
public string FontName
{
get { return fontName; }
set
{
if (string.IsNullOrEmpty(value))
return;
fontName = value;
if (spriteBatch != null)
videoFont = Game.Content.Load<SpriteFont>(fontName);
}
}
public Color Color
{
get { return textColor; }
set { textColor = value; }
}
public FPSDisplay(Game game)
: base(game)
{
}
public FPSDisplay(Game game, bool show)
: base(game)
{
Visible = show;
}
public FPSDisplay(Game game, string fontName)
: base(game)
{
this.fontName = fontName;
}
public FPSDisplay(Game game, string fontName, bool show)
: base(game)
{
this.fontName = fontName;
Visible = show;
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(Game.GraphicsDevice);
// Load the font if fontName has been set.
if (!string.IsNullOrEmpty(fontName))
videoFont = Game.Content.Load<SpriteFont>(fontName);
}
public override void Update(GameTime gameTime)
{
elapsedTime += (float)gameTime.ElapsedGameTime.TotalSeconds;
totalFrames++;
if (elapsedTime >= 1.0f)
{
fps = totalFrames;
totalFrames = 0;
elapsedTime = 0;
}
}
public override void Draw(GameTime gameTime)
{
if (fontName.Length > 0)
{
spriteBatch.Begin();
spriteBatch.DrawString(
videoFont,
"FPS=" + fps,
new Vector2(videoFont.LineSpacing),
textColor,
0f,
Vector2.Zero,
1f,
SpriteEffects.None,
0);
spriteBatch.End();
}
}
}