FrameRateCounter.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //-----------------------------------------------------------------------------
  2. // FrameRateCounter.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using System.Collections.Generic;
  9. using Microsoft.Xna.Framework;
  10. using Microsoft.Xna.Framework.Content;
  11. using Microsoft.Xna.Framework.Graphics;
  12. namespace CollisionSample
  13. {
  14. /// <summary>
  15. /// General Timing and Frame Rate Display Component.
  16. /// Add this to the GameComponentCollection to display the frame rate
  17. /// </summary>
  18. public class FrameRateCounter : DrawableGameComponent
  19. {
  20. ContentManager content;
  21. SpriteBatch spriteBatch;
  22. SpriteFont spriteFont;
  23. int frameRate = 0;
  24. int frameCounter = 0;
  25. TimeSpan elapsedTime = TimeSpan.Zero;
  26. /// <summary>
  27. /// Constructor which initializes the Content Manager which is used later for loading the font for display.
  28. /// </summary>
  29. /// <param name="game"></param>
  30. public FrameRateCounter(Game game)
  31. : base(game)
  32. {
  33. content = game.Content;
  34. }
  35. /// <summary>
  36. /// Graphics device objects are created here including the font.
  37. /// </summary>
  38. protected override void LoadContent()
  39. {
  40. spriteBatch = new SpriteBatch(GraphicsDevice);
  41. spriteFont = content.Load<SpriteFont>("Arial");
  42. }
  43. /// <summary>
  44. ///
  45. /// </summary>
  46. protected override void UnloadContent()
  47. {
  48. content.Unload();
  49. }
  50. /// <summary>
  51. /// The Update function is where the timing is measured and frame rate is computed.
  52. /// </summary>
  53. /// <param name="gameTime"></param>
  54. public override void Update(GameTime gameTime)
  55. {
  56. elapsedTime += gameTime.ElapsedGameTime;
  57. if (elapsedTime > TimeSpan.FromSeconds(1))
  58. {
  59. elapsedTime -= TimeSpan.FromSeconds(1);
  60. frameRate = frameCounter;
  61. frameCounter = 0;
  62. }
  63. }
  64. /// <summary>
  65. /// Frame rate display occurs during the Draw method and uses the Font and Sprite batch to render text.
  66. /// </summary>
  67. /// <param name="gameTime"></param>
  68. public override void Draw(GameTime gameTime)
  69. {
  70. frameCounter++;
  71. string fps = string.Format("fps: {0}", frameRate);
  72. spriteBatch.Begin();
  73. spriteBatch.DrawString(spriteFont, fps, new Vector2(32, 32), Color.White);
  74. spriteBatch.End();
  75. }
  76. }
  77. }