FPSCounterComponent.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework;
  4. namespace Microsoft.Xna.Samples.GameComponents
  5. {
  6. public class FPSCounterComponent : DrawableGameComponent
  7. {
  8. SpriteBatch spriteBatch;
  9. SpriteFont spriteFont;
  10. int frameRate = 0;
  11. int frameCounter = 0;
  12. TimeSpan elapsedTime = TimeSpan.Zero;
  13. public FPSCounterComponent(Game game, SpriteBatch Batch, SpriteFont Font)
  14. : base(game)
  15. {
  16. spriteFont = Font;
  17. spriteBatch = Batch;
  18. }
  19. public override void Update(GameTime gameTime)
  20. {
  21. elapsedTime += gameTime.ElapsedGameTime;
  22. if (elapsedTime > TimeSpan.FromSeconds(1))
  23. {
  24. elapsedTime -= TimeSpan.FromSeconds(1);
  25. frameRate = frameCounter;
  26. frameCounter = 0;
  27. }
  28. }
  29. public override void Draw(GameTime gameTime)
  30. {
  31. frameCounter++;
  32. string fps = string.Format("FPS: {0}", frameRate);
  33. spriteBatch.DrawString(spriteFont, fps, new Vector2(0, 0), Color.White);
  34. }
  35. }
  36. }