1
0
Fork 0
mirror of https://github.com/Ellpeck/MLEM.git synced 2024-06-04 22:23:37 +02:00
MLEM/MLEM.Ui/Elements/Paragraph.cs

68 lines
2.4 KiB
C#
Raw Normal View History

2019-08-09 19:28:48 +02:00
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;
2019-08-10 18:41:56 +02:00
public static float DefaultTextScale = 1;
2019-08-10 13:42:18 +02:00
2019-08-09 19:28:48 +02:00
private string text;
private float lineHeight;
private string[] splitText;
private readonly IGenericFont font;
private readonly bool centerText;
2019-08-10 18:41:56 +02:00
public float TextScale = DefaultTextScale;
2019-08-09 19:28:48 +02:00
public string Text {
get => this.text;
set {
this.text = value;
this.SetDirty();
}
}
2019-08-10 18:41:56 +02:00
public Paragraph(Anchor anchor, float width, string text, bool centerText = false, IGenericFont font = null) : base(anchor, new Vector2(width, 0)) {
2019-08-09 19:28:48 +02:00
this.text = text;
this.font = font ?? DefaultFont;
2019-08-09 19:28:48 +02:00
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();
2019-08-09 19:28:48 +02:00
this.lineHeight = 0;
var height = 0F;
foreach (var strg in this.splitText) {
var strgHeight = this.font.MeasureString(strg).Y * this.TextScale;
2019-08-09 19:28:48 +02:00
height += strgHeight + 1;
if (strgHeight > this.lineHeight)
this.lineHeight = strgHeight;
}
return new Point(size.X, height.Ceil());
}
2019-08-10 13:42:18 +02:00
public override void Draw(GameTime time, SpriteBatch batch, float alpha) {
base.Draw(time, batch, alpha);
2019-08-09 19:28:48 +02:00
var pos = this.DisplayArea.Location.ToVector2();
var offset = new Vector2();
foreach (var line in this.splitText) {
if (this.centerText) {
2019-08-10 13:42:18 +02:00
this.font.DrawCenteredString(batch, line, pos + offset + new Vector2(this.DisplayArea.Width / 2, 0), this.TextScale, Color.White * alpha);
2019-08-09 19:28:48 +02:00
} else {
2019-08-10 13:42:18 +02:00
this.font.DrawString(batch, line, pos + offset, Color.White * alpha, 0, Vector2.Zero, this.TextScale, SpriteEffects.None, 0);
2019-08-09 19:28:48 +02:00
}
offset.Y += this.lineHeight + 1;
}
}
}
}