Jump to content

C# Button Class


L B
 Share

Recommended Posts

Here you go with a simple implementation of my OOP drawing system. It's a simple button class that can be used in any way you like. Call "Button.Update()" right before "Graphics.Flip()". Feel free to make a list that updates all of them, I'm simply sharing this class. Couldn't make it part of any other release, really.

 

	public enum ButtonState
{
	Idle,
	Hover,
	Clicked,
	Down
}

public class Button
{
	public Texture IdleTexture { get; set; }
	public Texture HoverTexture { get; set; }
	public Texture ClickedTexture { get; set; }
	public Texture DownTexture { get; set; }

	public ButtonState State { get; private set; }
	public Image Image { get; private set; }

	public Button(Image image)
	{
		this.State = ButtonState.Idle;

		this.Image = image;

		this.IdleTexture = this.Image.Texture;
		this.ClickedTexture = this.Image.Texture;
		this.HoverTexture = this.Image.Texture;
		this.DownTexture = this.Image.Texture;
	}

	public void Update()
	{
		this.State = ButtonState.Idle;

		if (
			Mouse.X >= this.Image.X && 
			Mouse.Y >= this.Image.Y && 
			Mouse.X <= this.Image.X + this.Image.Width && 
			Mouse.Y <= this.Image.Y + this.Image.Height
			)
		{
			this.State = ButtonState.Hover;

			if (Mouse.ButtonDown(MouseButton.Left))
			{
				this.State = ButtonState.Down;
			}

			if (Mouse.ButtonHit(MouseButton.Left))
			{
				this.State = ButtonState.Clicked;
			}
		}

		switch (this.State)
		{
			case ButtonState.Clicked:
				this.Image.Texture = this.ClickedTexture;
				break;

			case ButtonState.Down:
				this.Image.Texture = this.DownTexture;
				break;

			case ButtonState.Hover:
				this.Image.Texture = this.HoverTexture;
				break;

			case ButtonState.Idle:
				this.Image.Texture = this.IdleTexture;
				break;
		}

		Drawing.SetBlend(BlendType.Alpha);
		this.Image.Draw();
		Drawing.SetBlend(BlendType.None);
	}	}

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...