Unity Text自动省略

需求

Text大小已知的情况下,将其超出文本框的内容省略(用其他字符替换)。

实现

        /// <summary>
        /// 超出文本框的部分用mask代替
        /// </summary>
        /// <param name="target">目标Text</param>
        /// <param name="content">原文本内容</param>
        /// <param name="mask">如果超出文本框 代替剩余文本的字符串</param>
        /// <param name="maxLine">限定行数</param>
        public static void EllipsisText(this UnityEngine.UI.Text target, string content, string mask, int maxLine = int.MaxValue - 1)
        {
    
    
            if (string.IsNullOrEmpty(content))
            {
    
    
                target.text = string.Empty;
                return;
            }

            var textGenerator = new UnityEngine.TextGenerator(content.Length);
            {
    
    
                var setting = target.GetGenerationSettings(target.rectTransform.rect.size);

                if (textGenerator.PopulateWithErrors(content, setting, target.gameObject))
                {
    
    
                    var endIndex = GetLineEndPosition(textGenerator, maxLine - 1);
                    {
    
    
                        if (endIndex < content.Length)
                        {
    
    
                            do
                            {
    
    
                                content = content.Substring(0, endIndex--);
                                textGenerator.PopulateWithErrors($"{
      
      content}{
      
      mask}", setting, target.gameObject);
                            }
                            while ((content.Length + mask.Length) != GetLineEndPosition(textGenerator, maxLine - 1));

                            content = $"{
      
      content}{
      
      mask}";
                        }
                    }
                }
                else
                {
    
    
                    UnityEngine.Debug.LogError("错误", target.gameObject);
                }

                target.text = content;
            }
        }
        /// <summary>
        /// 获取Text能显示出的最后一个字符的index
        /// </summary>
        /// <param name="generator">目标text</param>
        /// <param name="line">可以指定行数</param>
        /// <returns></returns>
        private static int GetLineEndPosition(UnityEngine.TextGenerator generator, int line = 0)
        {
    
    
            line = UnityEngine.Mathf.Max(line, 0);

            //当指定行数小于最大行数时 返回行尾字符的index
            if (line + 1 < generator.lines.Count)
            {
    
    
                return generator.lines[line + 1].startCharIdx - 1;
            }

            return generator.characterCountVisible;
        }

调用

        GetComponent<Text>().EllipsisText("原文本", "...");

猜你喜欢

转载自blog.csdn.net/weixin_44558405/article/details/129361524