Sprite.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using Microsoft.Xna.Framework;
  7. using Microsoft.Xna.Framework.Graphics;
  8. namespace Tutorial018.Sprites
  9. {
  10. public class Sprite : Component
  11. {
  12. protected Texture2D _rectangleTexture;
  13. protected Texture2D _texture;
  14. public Vector2 Position;
  15. public Rectangle Rectangle
  16. {
  17. get { return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height); }
  18. }
  19. public bool ShowRectangle { get; set; }
  20. public Sprite(Texture2D texture)
  21. {
  22. _texture = texture;
  23. ShowRectangle = false;
  24. }
  25. public Sprite(GraphicsDevice graphicsDevice, Texture2D texture)
  26. : this(texture)
  27. {
  28. SetRectangleTexture(graphicsDevice, texture);
  29. }
  30. private void SetRectangleTexture(GraphicsDevice graphicsDevice, Texture2D texture)
  31. {
  32. var colours = new List<Color>();
  33. for (int y = 0; y < texture.Height; y++)
  34. {
  35. for (int x = 0; x < texture.Width; x++)
  36. {
  37. if (y == 0 || // On the top
  38. x == 0 || // On the left
  39. y == texture.Height - 1 || // on the bottom
  40. x == texture.Width - 1) // on the right
  41. {
  42. colours.Add(new Color(255, 255, 255, 255)); // white
  43. }
  44. else
  45. {
  46. colours.Add(new Color(0, 0, 0, 0)); // transparent
  47. }
  48. }
  49. }
  50. _rectangleTexture = new Texture2D(graphicsDevice, texture.Width, texture.Height);
  51. _rectangleTexture.SetData<Color>(colours.ToArray());
  52. }
  53. public override void Update(GameTime gameTime)
  54. {
  55. }
  56. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  57. {
  58. spriteBatch.Draw(_texture, Position, Color.White);
  59. if (ShowRectangle)
  60. {
  61. if (_rectangleTexture != null)
  62. spriteBatch.Draw(_rectangleTexture, Position, Color.Red);
  63. }
  64. }
  65. }
  66. }