Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Calculating and Constraining Text Dimensions with TextMeshProUGUI in Unity

Tech 1

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...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

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...

Leave a Comment

Anonymous

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