AlignedSpriteBatch.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #region File Description
  2. //-----------------------------------------------------------------------------
  3. // AlignedSpriteBatch.cs
  4. //
  5. // Microsoft XNA Community Game Platform
  6. // Copyright (C) Microsoft Corporation. All rights reserved.
  7. //-----------------------------------------------------------------------------
  8. #endregion
  9. #region Using Statements
  10. using System;
  11. using Microsoft.Xna.Framework;
  12. using Microsoft.Xna.Framework.Graphics;
  13. #endregion
  14. namespace SafeArea
  15. {
  16. /// <summary>
  17. /// Flags enum defines the various ways a text string
  18. /// can be aligned relative to its specified position.
  19. /// </summary>
  20. [Flags]
  21. public enum Alignment
  22. {
  23. // Horizontal alignment options.
  24. Left = 0,
  25. Right = 1,
  26. HorizontalCenter = 2,
  27. // Vertical alignment options.
  28. Top = 0,
  29. Bottom = 4,
  30. VerticalCenter = 8,
  31. // Combined vertical + horizontal alignment options.
  32. TopLeft = Top | Left,
  33. TopRight = Top | Right,
  34. TopCenter = Top | HorizontalCenter,
  35. BottomLeft = Bottom | Left,
  36. BottomRight = Bottom | Right,
  37. BottomCenter = Bottom | HorizontalCenter,
  38. CenterLeft = VerticalCenter | Left,
  39. CenterRight = VerticalCenter | Right,
  40. Center = VerticalCenter | HorizontalCenter,
  41. }
  42. /// <summary>
  43. /// This class derives from the built in SpriteBatch, adding new
  44. /// logic for aligning text strings in more varied ways than just
  45. /// the default top left alignment.
  46. /// </summary>
  47. public class AlignedSpriteBatch : SpriteBatch
  48. {
  49. /// <summary>
  50. /// Constructor.
  51. /// </summary>
  52. public AlignedSpriteBatch(GraphicsDevice graphicsDevice)
  53. : base(graphicsDevice)
  54. { }
  55. /// <summary>
  56. /// Draws a text string with the specified alignment.
  57. /// </summary>
  58. public void DrawString(SpriteFont spriteFont, string text,
  59. Vector2 position, Color color, Alignment alignment)
  60. {
  61. // Compute horizontal alignment.
  62. if ((alignment & Alignment.Right) != 0)
  63. {
  64. position.X -= spriteFont.MeasureString(text).X;
  65. }
  66. else if ((alignment & Alignment.HorizontalCenter) != 0)
  67. {
  68. position.X -= spriteFont.MeasureString(text).X / 2;
  69. }
  70. // Compute vertical alignment.
  71. if ((alignment & Alignment.Bottom) != 0)
  72. {
  73. position.Y -= spriteFont.LineSpacing;
  74. }
  75. else if ((alignment & Alignment.VerticalCenter) != 0)
  76. {
  77. position.Y -= spriteFont.LineSpacing / 2;
  78. }
  79. // Draw the string.
  80. DrawString(spriteFont, text, position, color);
  81. }
  82. }
  83. }