显示fps的DrawableGameComponent组件
还是用DrawableGameComponent比较方便管理。
#region Using Statements
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace Jewels {
public class FrameRateCounter : DrawableGameComponent {
ContentManager content;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
int frameRate = 0;
int frameCounter = 0;
TimeSpan elapsedTime = TimeSpan.Zero;
Game parentGame;
public FrameRateCounter(Game game)
: base(game) {
parentGame = game;
content = new ContentManager(game.Services, Jewels.Game.CONTENT_DIR);
}
protected override void LoadContent() {
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = content.Load<SpriteFont>("fpsfont");
}
protected override void UnloadContent() {
content.Unload();
}
public override void Update(GameTime gameTime) {
elapsedTime += gameTime.ElapsedGameTime;
if (elapsedTime > TimeSpan.FromSeconds(1)) {
elapsedTime -= TimeSpan.FromSeconds(1);
frameRate = frameCounter;
frameCounter = 0;
}
}
public override void Draw(GameTime gameTime) {
frameCounter++;
string fps = string.Format("FPS: {0}", frameRate);
Vector2 pos = new Vector2(parentGame.ViewportWidth - 100, parentGame.ViewportHeight / 2);
spriteBatch.Begin();
spriteBatch.DrawString(spriteFont, fps, new Vector2(pos.X + 1, pos.Y + 1), Color.Black);
spriteBatch.DrawString(spriteFont, fps, pos, Color.White);
spriteBatch.End();
}
}
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
#endregion
namespace Jewels {
public class FrameRateCounter : DrawableGameComponent {
ContentManager content;
SpriteBatch spriteBatch;
SpriteFont spriteFont;
int frameRate = 0;
int frameCounter = 0;
TimeSpan elapsedTime = TimeSpan.Zero;
Game parentGame;
public FrameRateCounter(Game game)
: base(game) {
parentGame = game;
content = new ContentManager(game.Services, Jewels.Game.CONTENT_DIR);
}
protected override void LoadContent() {
spriteBatch = new SpriteBatch(GraphicsDevice);
spriteFont = content.Load<SpriteFont>("fpsfont");
}
protected override void UnloadContent() {
content.Unload();
}
public override void Update(GameTime gameTime) {
elapsedTime += gameTime.ElapsedGameTime;
if (elapsedTime > TimeSpan.FromSeconds(1)) {
elapsedTime -= TimeSpan.FromSeconds(1);
frameRate = frameCounter;
frameCounter = 0;
}
}
public override void Draw(GameTime gameTime) {
frameCounter++;
string fps = string.Format("FPS: {0}", frameRate);
Vector2 pos = new Vector2(parentGame.ViewportWidth - 100, parentGame.ViewportHeight / 2);
spriteBatch.Begin();
spriteBatch.DrawString(spriteFont, fps, new Vector2(pos.X + 1, pos.Y + 1), Color.Black);
spriteBatch.DrawString(spriteFont, fps, pos, Color.White);
spriteBatch.End();
}
}
}