using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using RhythmBullet.Zer01HD.Utilities.Camera; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RhythmBullet.Zer01HD.UI.Modular.Modules { public class Text : UIModule { private SpriteFont font; private float scale; private Vector2 position; private string text; private Vector2 textSize; public bool autoWrap; public bool autoScale; public string DisplayedText { get { return text; } set { textSize = font.MeasureString(value); text = value; } } public Text(string displayedText, SpriteFont font, int height) { bounds.Height = height; this.font = font; } public override void Update(GameTime gameTime) { position.X = bounds.X; position.Y = bounds.Y; if (autoWrap) { AttemptToWrapText(); } if (autoScale) { AttemptToScaleFont(); } base.Update(gameTime); } public override void Draw(SpriteBatch batch) { batch.DrawString(font, DisplayedText, position, color, 0f, origin, scale, SpriteEffects.None, 0f); base.Draw(batch); } public void AttemptToScaleFont() { if (textSize.X * scale > bounds.Width || textSize.X * scale < bounds.Width) { scale = bounds.Width / textSize.X; } if (textSize.Y * scale > bounds.Height || textSize.Y *scale > bounds.Height) { scale = bounds.Height / textSize.Y; } } public void RemoveLineBreaks() { DisplayedText = DisplayedText.Replace("\n", " "); } public void AttemptToWrapText(bool unwrap = false) { if (unwrap) RemoveLineBreaks(); if (textSize.X * scale > bounds.Width) { text = text.Replace("\n", " "); string[] words = text.Split(' '); StringBuilder stringBuilder = new StringBuilder(); float currentScaledLineWidth = 0f; for (int w = 0; w < words.Length; w++) { string word = words[w]; float scaledWidth = font.MeasureString(word).X * scale; if (currentScaledLineWidth + scaledWidth <= bounds.Width) { stringBuilder.Append(word); currentScaledLineWidth += scaledWidth; } else { stringBuilder.AppendLine(); currentScaledLineWidth = 0; } } DisplayedText = stringBuilder.ToString(); } } } }