Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Calculating and Constraining Text Dimensions with TextMeshProUGUI in Unity

Tech Apr 20 9

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);
        }
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

SBUS Signal Analysis and Communication Implementation Using STM32 with Fus Remote Controller

Overview In a recent project, I utilized the SBUS protocol with the Fus remote controller to control a vehicle's basic operations, including movement, lights, and mode switching. This article is aimed...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.