Button.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 Tutorial020.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 EventHandler Click;
  22. public bool Clicked { get; private set; }
  23. public float Layer { get; set; }
  24. public Vector2 Origin
  25. {
  26. get
  27. {
  28. return new Vector2(_texture.Width / 2, _texture.Height / 2);
  29. }
  30. }
  31. public Color PenColour { get; set; }
  32. public Vector2 Position { get; set; }
  33. public Rectangle Rectangle
  34. {
  35. get
  36. {
  37. return new Rectangle((int)Position.X - ((int)Origin.X), (int)Position.Y - (int)Origin.Y, _texture.Width, _texture.Height);
  38. }
  39. }
  40. public string Text;
  41. #endregion
  42. #region Methods
  43. public Button(Texture2D texture, SpriteFont font)
  44. {
  45. _texture = texture;
  46. _font = font;
  47. PenColour = Color.Black;
  48. }
  49. public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
  50. {
  51. var colour = Color.White;
  52. if (_isHovering)
  53. colour = Color.Gray;
  54. spriteBatch.Draw(_texture, Position, null, colour, 0f, Origin, 1f, SpriteEffects.None, Layer);
  55. if (!string.IsNullOrEmpty(Text))
  56. {
  57. var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
  58. var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
  59. spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour, 0f, new Vector2(0, 0), 1f, SpriteEffects.None, Layer + 0.01f);
  60. }
  61. }
  62. public override void Update(GameTime gameTime)
  63. {
  64. _previousMouse = _currentMouse;
  65. _currentMouse = Mouse.GetState();
  66. var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
  67. _isHovering = false;
  68. if (mouseRectangle.Intersects(Rectangle))
  69. {
  70. _isHovering = true;
  71. if (_currentMouse.LeftButton == ButtonState.Released && _previousMouse.LeftButton == ButtonState.Pressed)
  72. {
  73. Click?.Invoke(this, new EventArgs());
  74. }
  75. }
  76. }
  77. #endregion
  78. }
  79. }