/// <summary>
    /// This is a game component that implements IUpdateable.
    /// </summary>
    public class FrameRateCounter : Microsoft.Xna.Framework.DrawableGameComponent
    {
        ContentManager content;
        SpriteBatch spriteBatch;
        SpriteFont spriteFont;

        int frameRate = 0;
        int frameCounter = 0;
        TimeSpan elapsedTime = TimeSpan.Zero;

        public FrameRateCounter(Game game, SpriteBatch spriteBatch)
            : base(game)
        {
            content = new ContentManager(game.Services);
            LoadGraphicsContent(true);
            this.spriteBatch = spriteBatch;
        }

        protected void LoadGraphicsContent(bool loadAllContent)
        {
            if (loadAllContent)
            {
                spriteFont = content.Load<SpriteFont>(@"Content\HudFont");   // 指定SpriteFont
            }
        }

        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);

            spriteBatch.Begin();

            spriteBatch.DrawString(spriteFont, fps, new Vector2(20, 20), Color.White);    // 坐标根据需要自行修改

            spriteBatch.End();
        }
    }

需要用的时候只要在LoadContent的spriteBatch初始化之后用

Component.Add(new FrameRateCounter(this, spriteBatch));

即可。

 

另外注意,需要自行修改一下你用来显示FPS的SpriteFont文件,和要显示FPS的坐标。

posted on 2012-07-03 17:57  The_Fake  阅读(844)  评论(0编辑  收藏  举报