Button.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. using Microsoft.Xna.Framework.Input;
  9. namespace Tutorial029.Controls
  10. {
  11. public class Button : Component
  12. {
  13. protected MouseState _previousMouse;
  14. protected MouseState _currentMouse;
  15. protected Texture2D _texture;
  16. protected SpriteFont _font;
  17. protected Color _colour;
  18. public Vector2 Position;
  19. public Rectangle Rectangle
  20. {
  21. get
  22. {
  23. return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
  24. }
  25. }
  26. public Color PenColour { get; set; }
  27. public string Text { get; set; }
  28. public bool IsHovering { get; set; }
  29. public Action OnClick { get; set; }
  30. public Button(Texture2D texture)
  31. : this(texture, null)
  32. {
  33. }
  34. public Button(Texture2D texture, SpriteFont font)
  35. {
  36. _texture = texture;
  37. _font = font;
  38. Text = "";
  39. PenColour = Color.White;
  40. }
  41. public override void Update(GameTime gameTime)
  42. {
  43. _previousMouse = _currentMouse;
  44. _currentMouse = Mouse.GetState();
  45. var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
  46. IsHovering = false;
  47. _colour = Color.White;
  48. if (mouseRectangle.Intersects(Rectangle))
  49. {
  50. IsHovering = true;
  51. OnHover();
  52. if (_previousMouse.LeftButton == ButtonState.Pressed && _currentMouse.LeftButton == ButtonState.Released)
  53. {
  54. OnClick?.Invoke();
  55. }
  56. }
  57. }
  58. protected virtual void OnHover()
  59. {
  60. _colour = Color.Yellow;
  61. }
  62. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  63. {
  64. spriteBatch.Draw(_texture, Position, _colour);
  65. if (_font != null)
  66. {
  67. var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
  68. var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
  69. spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
  70. }
  71. }
  72. }
  73. }