Button.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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 Tutorial030.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. _colour = Color.Yellow;
  52. if (_previousMouse.LeftButton == ButtonState.Pressed && _currentMouse.LeftButton == ButtonState.Released)
  53. {
  54. OnClick?.Invoke();
  55. }
  56. }
  57. }
  58. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  59. {
  60. spriteBatch.Draw(_texture, Position, _colour);
  61. if (_font != null)
  62. {
  63. var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
  64. var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
  65. spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
  66. }
  67. }
  68. }
  69. }