| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using Microsoft.Xna.Framework;
- using Microsoft.Xna.Framework.Graphics;
- using Microsoft.Xna.Framework.Input;
- namespace Tutorial029.Controls
- {
- public class Button : Component
- {
- protected MouseState _previousMouse;
- protected MouseState _currentMouse;
- protected Texture2D _texture;
- protected SpriteFont _font;
- protected Color _colour;
- public Vector2 Position;
- public Rectangle Rectangle
- {
- get
- {
- return new Rectangle((int)Position.X, (int)Position.Y, _texture.Width, _texture.Height);
- }
- }
- public Color PenColour { get; set; }
- public string Text { get; set; }
- public bool IsHovering { get; set; }
- public Action OnClick { get; set; }
- public Button(Texture2D texture)
- : this(texture, null)
- {
- }
- public Button(Texture2D texture, SpriteFont font)
- {
- _texture = texture;
- _font = font;
- Text = "";
- PenColour = Color.White;
- }
- public override void Update(GameTime gameTime)
- {
- _previousMouse = _currentMouse;
- _currentMouse = Mouse.GetState();
- var mouseRectangle = new Rectangle(_currentMouse.X, _currentMouse.Y, 1, 1);
- IsHovering = false;
- _colour = Color.White;
- if (mouseRectangle.Intersects(Rectangle))
- {
- IsHovering = true;
- OnHover();
- if (_previousMouse.LeftButton == ButtonState.Pressed && _currentMouse.LeftButton == ButtonState.Released)
- {
- OnClick?.Invoke();
- }
- }
- }
- protected virtual void OnHover()
- {
- _colour = Color.Yellow;
- }
- public override void Draw(GameTime gameTime, SpriteBatch spriteBatch)
- {
- spriteBatch.Draw(_texture, Position, _colour);
- if (_font != null)
- {
- var x = (Rectangle.X + (Rectangle.Width / 2)) - (_font.MeasureString(Text).X / 2);
- var y = (Rectangle.Y + (Rectangle.Height / 2)) - (_font.MeasureString(Text).Y / 2);
- spriteBatch.DrawString(_font, Text, new Vector2(x, y), PenColour);
- }
- }
- }
- }
|