1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-06-24 13:50:04 +02:00
MLEM/MLEM.Ui/Elements/Paragraph.cs
2019-08-10 19:23:08 +02:00

68 lines
2.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using MLEM.Extensions;
using MLEM.Font;
namespace MLEM.Ui.Elements {
public class Paragraph : Element {
public static IGenericFont DefaultFont;
public static float DefaultTextScale = 1;
private string text;
private float lineHeight;
private string[] splitText;
private readonly IGenericFont font;
private readonly bool centerText;
public float TextScale = DefaultTextScale;
public string Text {
get => this.text;
set {
this.text = value;
this.SetDirty();
}
}
public Paragraph(Anchor anchor, float width, string text, bool centerText = false, IGenericFont font = null) : base(anchor, new Vector2(width, 0)) {
this.text = text;
this.font = font ?? DefaultFont;
this.centerText = centerText;
}
protected override Point CalcActualSize(Rectangle parentArea) {
var size = base.CalcActualSize(parentArea);
this.splitText = this.font.SplitString(this.text, size.X, this.TextScale).ToArray();
this.lineHeight = 0;
var height = 0F;
foreach (var strg in this.splitText) {
var strgHeight = this.font.MeasureString(strg).Y * this.TextScale;
height += strgHeight + 1;
if (strgHeight > this.lineHeight)
this.lineHeight = strgHeight;
}
return new Point(size.X, height.Ceil());
}
public override void Draw(GameTime time, SpriteBatch batch, float alpha) {
base.Draw(time, batch, alpha);
var pos = this.DisplayArea.Location.ToVector2();
var offset = new Vector2();
foreach (var line in this.splitText) {
if (this.centerText) {
this.font.DrawCenteredString(batch, line, pos + offset + new Vector2(this.DisplayArea.Width / 2, 0), this.TextScale, Color.White * alpha);
} else {
this.font.DrawString(batch, line, pos + offset, Color.White * alpha, 0, Vector2.Zero, this.TextScale, SpriteEffects.None, 0);
}
offset.Y += this.lineHeight + 1;
}
}
}
}