OneNightDuel/ONDClient/GUI/TextUIElement.cs

84 lines
2.8 KiB
C#
Raw Permalink Normal View History

using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace ONDClient.GUI;
public class TextUIElement : UIElement {
public SpriteFont Font { get; set; }
public Alignment CurrentAlignment { get; set; }
public string Text{
get;
set{
field = value;
if(AutoBounds)
Bounds = (Bounds.Item1, Bounds.Item1 + new Point((int)Measure().X, (int)Measure().Y));
}
} = "";
public Color Color{ get; set; } = Color.White;
public bool AutoBounds{ get; protected set; } = false;
private Vector2 origin;
private const float UNIVERSAL_TEXT_SCALE_MULTIPLIER = 0.3f;
public TextUIElement(Point corner1, SpriteFont font, Alignment alignment = Alignment.LEFT, bool autoBounds = true) : base(corner1, corner1) {
Font = font;
AutoBounds = autoBounds;
Align(alignment);
Visible = true;
}
public TextUIElement(Point corner1, Point corner2, SpriteFont font, Alignment alignment = Alignment.LEFT) : base(corner1, corner2) {
Font = font;
Align(alignment);
Visible = true;
}
public override void Draw(SpriteBatch spriteBatch) {
if(!Visible || !Active) return;
base.Draw(spriteBatch);
align();
spriteBatch.DrawString(Font, Text, ScreenSpaceBounds.Item1.ToVector2(), Color, 0, origin, pixelScaleMultiplier * UNIVERSAL_TEXT_SCALE_MULTIPLIER, SpriteEffects.None, 0);
}
public void Align(Alignment alignment) {
CurrentAlignment = alignment;
switch (alignment){
case Alignment.LEFT:
AlignLeft();
break;
case Alignment.RIGHT:
AlignRight();
break;
case Alignment.CENTER:
AlignCenter();
break;
}
}
protected override void UpdateBounds() {
Point inSpaceOrigin = Bounds.Item1 + origin.ToPoint();
_bounds = ((Bounds.Item1 - inSpaceOrigin).MultiplyByScalar(ScaleMultiplier) + inSpaceOrigin, (Bounds.Item2 - Bounds.Item1).MultiplyByScalar(ScaleMultiplier) + inSpaceOrigin);
ScreenSpaceBounds = (Bounds.Item1.MultiplyByScalar(pixelScaleMultiplier), Bounds.Item2.MultiplyByScalar(pixelScaleMultiplier));
Align(CurrentAlignment);
}
public Vector2 Measure() => Font.MeasureString(Text) * UNIVERSAL_TEXT_SCALE_MULTIPLIER * ScaleMultiplier;
private void AlignLeft() {
align = () => origin = Vector2.Zero;
}
private void AlignRight() {
align = () => origin = Font.MeasureString(Text) * ScaleMultiplier;
}
private void AlignCenter() {
align = () => origin = new(Font.MeasureString(Text).X * ScaleMultiplier / 2, 0);
}
private Action align;
public enum Alignment {
LEFT, RIGHT, CENTER
}
}