thefake
    /// <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的坐标。

分类:

技术点:

相关文章:

  • 2021-08-29
  • 2021-07-29
  • 2021-04-01
  • 2021-08-29
  • 2021-07-04
  • 2021-09-24
  • 2021-04-16
猜你喜欢
  • 2021-11-27
  • 2021-08-14
  • 2021-09-09
  • 2021-08-14
  • 2021-09-08
  • 2021-04-30
相关资源
相似解决方案