CommonGraphics.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. //-----------------------------------------------------------------------------
  2. // CommonGraphics.cs
  3. //
  4. // Microsoft XNA Community Game Platform
  5. // Copyright (C) Microsoft Corporation. All rights reserved.
  6. //-----------------------------------------------------------------------------
  7. using System;
  8. using Microsoft.Xna.Framework;
  9. using Microsoft.Xna.Framework.Graphics;
  10. namespace UserInterfaceSample
  11. {
  12. public static class CommonGraphics
  13. {
  14. /// <summary>
  15. /// Draw a string centered in the given rectangle
  16. /// </summary>
  17. public static void DrawCenteredText(SpriteBatch batch, SpriteFont font, Rectangle rectangle, string text, Color color)
  18. {
  19. if (!string.IsNullOrEmpty(text))
  20. {
  21. Vector2 size = font.MeasureString(text);
  22. Vector2 topLeft = new Vector2(rectangle.Center.X, rectangle.Center.Y) - size * 0.5f;
  23. batch.DrawString(font, text, topLeft, color);
  24. }
  25. }
  26. /// <summary>
  27. /// Draw the outline of a rectangle using the given SpriteBatch. The supplied texture should be
  28. /// a single-pixel blank white texture such as ScreenManager.BlankTexture. This function
  29. /// does not call Begin/End on the batch; you need to do that outside of this call.
  30. /// </summary>
  31. public static void DrawRectangle(SpriteBatch batch, Texture2D blankTexture, Rectangle rectangle, Color color)
  32. {
  33. DrawSpriteLine(batch, blankTexture, new Vector2(rectangle.Left, rectangle.Top), new Vector2(rectangle.Right, rectangle.Top));
  34. DrawSpriteLine(batch, blankTexture, new Vector2(rectangle.Left, rectangle.Bottom), new Vector2(rectangle.Right, rectangle.Bottom));
  35. DrawSpriteLine(batch, blankTexture, new Vector2(rectangle.Left, rectangle.Top), new Vector2(rectangle.Left, rectangle.Bottom));
  36. DrawSpriteLine(batch, blankTexture, new Vector2(rectangle.Right, rectangle.Top), new Vector2(rectangle.Right, rectangle.Bottom));
  37. }
  38. private static void DrawSpriteLine(SpriteBatch batch, Texture2D blankTexture, Vector2 vector1, Vector2 vector2)
  39. {
  40. float distance = Vector2.Distance(vector1, vector2);
  41. float angle = (float)Math.Atan2((vector2.Y - vector1.Y), (vector2.X - vector1.X));
  42. // stretch the pixel between the two vectors
  43. batch.Draw(blankTexture,
  44. vector1,
  45. null,
  46. Color.White,
  47. angle,
  48. Vector2.Zero,
  49. new Vector2(distance, 1),
  50. SpriteEffects.None,
  51. 0);
  52. }
  53. }
  54. }