Button.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using Microsoft.Xna.Framework;
  2. using Microsoft.Xna.Framework.Graphics;
  3. using Microsoft.Xna.Framework.Input;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace Tutorial015.Controls
  10. {
  11. public class Button : Component
  12. {
  13. #region Fields
  14. private MouseState _currentMouse;
  15. private SpriteFont _font;
  16. private bool _isHovering;
  17. private MouseState _previousMouse;
  18. private Texture2D _texture;
  19. #endregion
  20. #region Properties
  21. public event EventHandler Click;
  22. public bool Clicked { get; private set; }
  23. public Color PenColour { get; set; }
  24. public Vector2 Position { get; set; }
  25. public Rectangle Rectangle
  26. {
  27. get
  28. {
  29. return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
  30. }
  31. }
  32. public string Text;
  33. #endregion
  34. #region Methods
  35. public Button(Texture2D texture, SpriteFont font)
  36. {
  37. _texture = texture;
  38. _font = font;
  39. PenColour = Color.Black;
  40. }
  41. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  42. {
  43. var colour = Color.White;
  44. if (_isHovering)
  45. colour = Color.Gray;
  46. spriteBatch.Draw(_texture, Rectangle, colour);
  47. if (!string.IsNullOrEmpty(Text))
  48. {
  49. var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
  50. var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
  51. spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
  52. }
  53. }
  54. public override void Update(GameTime gameTime)
  55. {
  56. _previousMouse = _currentMouse;
  57. _currentMouse = Mouse.GetState();
  58. var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
  59. _isHovering = false;
  60. if (mouseRectangle.Intersects(Rectangle))
  61. {
  62. _isHovering = true;
  63. if (_currentMouse.LeftButton == ButtonState.Released && _previousMouse.LeftButton == ButtonState.Pressed)
  64. {
  65. Click?.Invoke(this, new EventArgs());
  66. }
  67. }
  68. }
  69. #endregion
  70. }
  71. }