Calculating and Constraining Text Dimensions with TextMeshProUGUI in Unity
When automatic resiizng via ContentSizeFitter proves insufficient, manual calculation of text dimensions becomes necessary. Force layout updates using LayoutRebuilder.ForceRebuildLayoutImmediate() when required.
using TMPro;
using UnityEngine;
public static class TMPDimensionUtility
{
public static Vector2 ConstrainToWidth(this TextMeshProUGUI tmpComponent, string content, float maxWidth)
{
Vector2 computedSize = tmpComponent.GetPreferredValues(content, maxWidth, 0);
tmpComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, maxWidth);
tmpComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, computedSize.y);
tmpComponent.text = content;
return new Vector2(maxWidth, computedSize.y);
}
public static Vector2 ConstrainToHeight(this TextMeshProUGUI tmpComponent, string content, float maxHeight)
{
Vector2 computedSize = tmpComponent.GetPreferredValues(content, 0, maxHeight);
tmpComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, computedSize.x);
tmpComponent.rectTransform.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, maxHeight);
tmpComponent.text = content;
return new Vector2(computedSize.x, maxHeight);
}
}
Usage example:
using TMPro;
using UnityEngine;
public class DimensionConstraintDemo : MonoBehaviour
{
public TextMeshProUGUI displayText;
[TextArea(5, 15)]
public string sampleContent;
public float widthLimit;
public float heightLimit;
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
displayText.ConstrainToWidth(sampleContent, widthLimit);
}
if (Input.GetKeyDown(KeyCode.A))
{
displayText.ConstrainToHeight(sampleContent, heightLimit);
}
}
}