2019年8月26日 星期一

[C#, Unity] Unity Text text super box with ‘...’ ellipsis at the end

public void SetTextWithEllipsis(Text textComponent, string value)
        {
            var generator = new TextGenerator();
            var rectTransform = textComponent.GetComponent<RectTransform>();
            var settings = textComponent.GetGenerationSettings(rectTransform.rect.size);
            generator.Populate(value, settings);
            var characterCountVisible = generator.characterCountVisible;
            var updatedText = value;
            if (value.Length > characterCountVisible)
            {
                updatedText = value.Substring(0, characterCountVisible - 3);
                updatedText += "…";
            }
            textComponent.text = updatedText;
        }


Example:

Transform tt = gameObject.transform.Find("Text");
SetTextWithEllipsis(tt.gameObject.GetComponent<Text>(), "fffffffffffffffffffffffff");


沒有留言:

張貼留言