54 lines
1.6 KiB
C#
54 lines
1.6 KiB
C#
|
|
using UnityEngine;
|
|
using UnityEngine.UI;
|
|
|
|
/// <summary>
|
|
/// Text (UGUI) 组件扩展类
|
|
/// 功能
|
|
/// 实现文字过长省略号显示
|
|
/// </summary>
|
|
public static class TextExtension
|
|
{
|
|
// operating in no overflow (Horizonal|Vertical)
|
|
public static void SetTextWithEllipsis(this Text textComponent, string value)
|
|
{
|
|
// create generator with value and current Rect
|
|
var generator = new TextGenerator();
|
|
var rectTransform = textComponent.GetComponent<RectTransform>();
|
|
var settings = textComponent.GetGenerationSettings(rectTransform.rect.size);
|
|
generator.Populate(value, settings);
|
|
|
|
// truncate visible value and add ellipsis
|
|
var characterCountVisible = generator.characterCountVisible;
|
|
var updatedText = value;
|
|
if (value.Length > characterCountVisible)
|
|
{
|
|
updatedText = value.Substring(0, characterCountVisible - 1);
|
|
updatedText += "…";
|
|
}
|
|
|
|
// update text
|
|
textComponent.text = updatedText;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Unity 2019 版本以上
|
|
/// </summary>
|
|
/// <param name="textComponent"></param>
|
|
/// <param name="value"></param>
|
|
public static void SetTextWithEllipsis(this Text textComponent, string value, int characterVisibleCount)
|
|
{
|
|
|
|
var updatedText = value;
|
|
|
|
// 判断是否需要过长显示省略号
|
|
if (value.Length > characterVisibleCount)
|
|
{
|
|
updatedText = value.Substring(0, characterVisibleCount - 1);
|
|
updatedText += "…";
|
|
}
|
|
|
|
// update text
|
|
textComponent.text = updatedText;
|
|
}
|
|
} |