1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-11-26 22:48:34 +01:00
MLEM/MLEM.Ui/Elements/Checkbox.cs

76 lines
2.9 KiB
C#
Raw Normal View History

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MLEM.Extensions;
using MLEM.Input;
using MLEM.Misc;
using MLEM.Textures;
using MLEM.Ui.Style;
namespace MLEM.Ui.Elements {
public class Checkbox : Element {
public StyleProp<NinePatch> Texture;
public StyleProp<NinePatch> HoveredTexture;
public StyleProp<Color> HoveredColor;
public StyleProp<TextureRegion> Checkmark;
public Paragraph Label;
2019-08-24 00:07:54 +02:00
public float TextOffsetX = 2;
private bool checced;
public bool Checked {
get => this.checced;
set {
if (this.checced != value) {
this.checced = value;
this.OnCheckStateChange?.Invoke(this, this.checced);
}
}
}
public CheckStateChange OnCheckStateChange;
public Checkbox(Anchor anchor, Vector2 size, string label, bool defaultChecked = false) : base(anchor, size) {
this.checced = defaultChecked;
this.OnPressed += element => this.Checked = !this.Checked;
if (label != null) {
2019-08-24 00:07:54 +02:00
this.Label = new Paragraph(Anchor.CenterLeft, 0, label);
this.AddChild(this.Label);
}
}
protected override Vector2 CalcActualSize(RectangleF parentArea) {
var size = base.CalcActualSize(parentArea);
2019-08-24 00:07:54 +02:00
if (this.Label != null) {
this.Label.Size = new Vector2((size.X - size.Y) / this.Scale - this.TextOffsetX, 1);
this.Label.PositionOffset = new Vector2(size.Y / this.Scale + this.TextOffsetX, 0);
}
return size;
}
public override void Draw(GameTime time, SpriteBatch batch, float alpha, BlendState blendState, SamplerState samplerState, Matrix matrix) {
var tex = this.Texture;
var color = Color.White * alpha;
if (this.IsMouseOver) {
2019-11-05 13:28:41 +01:00
tex = this.HoveredTexture.OrDefault(tex);
color = (Color) this.HoveredColor * alpha;
}
var boxDisplayArea = new RectangleF(this.DisplayArea.Location, new Vector2(this.DisplayArea.Height));
batch.Draw(tex, boxDisplayArea, color, this.Scale);
if (this.Checked)
batch.Draw(this.Checkmark, boxDisplayArea, Color.White * alpha);
base.Draw(time, batch, alpha, blendState, samplerState, matrix);
}
protected override void InitStyle(UiStyle style) {
base.InitStyle(style);
this.Texture.SetFromStyle(style.CheckboxTexture);
this.HoveredTexture.SetFromStyle(style.CheckboxHoveredTexture);
this.HoveredColor.SetFromStyle(style.CheckboxHoveredColor);
this.Checkmark.SetFromStyle(style.CheckboxCheckmark);
}
public delegate void CheckStateChange(Checkbox box, bool checced);
}
}