recrownedgtk/RecrownedAthenaeum/UI/Modular/Modules/Interactive/Button.cs

102 lines
3.0 KiB
C#

using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using RecrownedAthenaeum.UI.Modular;
using RecrownedAthenaeum.DataTypes;
using RecrownedAthenaeum.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RecrownedAthenaeum.UI.Skin.Definitions;
namespace RecrownedAthenaeum.UI.Modular.Modules.Interactive
{
public delegate bool Clicked();
public class Button : UIModule
{
private ButtonSkinDefinition skinDefinition;
private ISpecialDrawable downTexture, upTexture, highlightedTexture, disabledTexture;
public event Clicked Listeners;
private bool pressed;
public bool disabled = false;
public bool Highlighted { get; private set; }
public Button(ISpecialDrawable down, ISpecialDrawable up, ISpecialDrawable disabled = null, ISpecialDrawable selected = null)
{
this.downTexture = down;
this.upTexture = up;
this.disabledTexture = disabled;
this.highlightedTexture = selected;
}
public Button(Skin.Skin skin, string definitionName = null)
{
this.skinDefinition = skin.ObtainDefinition<ButtonSkinDefinition>(definitionName, GetType());
downTexture = skin.textureAtlas[skinDefinition.downRegion];
upTexture = skin.textureAtlas[skinDefinition.upRegion];
disabledTexture = skin.textureAtlas[skinDefinition.disabledRegion];
highlightedTexture = skin.textureAtlas[skinDefinition.selectedRegion];
}
public override void Draw(SpriteBatch batch)
{
if (disabled)
{
disabledTexture?.Draw(batch, bounds, color);
}
else
{
if (pressed)
{
downTexture.Draw(batch, bounds, color);
}
else
{
upTexture.Draw(batch, bounds, color);
}
}
base.Draw(batch);
}
public sealed override bool MouseStateChanged(MouseState state)
{
if (InputUtilities.MouseWithinBoundries(bounds))
{
if (state.LeftButton == ButtonState.Pressed)
{
pressed = true;
}
else
{
pressed = false;
}
if (InputUtilities.MouseClicked())
{
OnClick();
}
Highlighted = true;
}
else
{
Highlighted = false;
pressed = false;
}
return base.MouseStateChanged(state);
}
public sealed override bool KeyboardStateChanged(KeyboardState state)
{
return base.KeyboardStateChanged(state);
}
protected void OnClick()
{
Listeners?.Invoke();
}
}
}