FPSCounterComponent.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. using System;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework;
  4. namespace Microsoft.Xna.Samples.BouncingBox
  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(1, 1), Color.Black);
  34. spriteBatch.DrawString(spriteFont, fps, new Vector2(0, 0), Color.White);
  35. }
  36. }
  37. }