【UGUI】UGUI 文字背景根据文字大小自适应

来源:互联网 发布:初学钢琴软件 编辑:程序博客网 时间:2024/05/16 08:05

在使用UGUI 的时候经常会做文字的适配,就是当文字字数超出文本以后让文本随字体的数量增加而加长或加宽,当有背景去做适配的时候如何去做呢?


道理是一样的 在text + contentSizeFitter 组件

然后根据文本最后的高度去对背景进行赋值,理论上 这很简单。

text.preferredHeight

但是 在项目中遇到了一个问题,就是当理想高度不准确的时候,怎么做?

后来的思路是 用  理想宽度去除以 /  字体的总长度 = 每个字体的宽度

用文本的固定宽度去除以 / 每个字体的宽度 = 得出一行有几个字

字体的总长度 除以 / 一行有几个字 = 得出总共有几行

大概这个思路就可以得出想要的高度

TextGenerator m_TextGenerator = stepText.cachedTextGeneratorForLayout;            TextGenerationSettings m_TextGenerationSettings = stepText.GetGenerationSettings(Vector2.zero);            m_TextGenerationSettings = stepText.GetGenerationSettings(new Vector2(stepText.rectTransform.rect.x, 0.0f));            float fHeight = m_TextGenerator.GetPreferredHeight(block.StepList[i].Desc, m_TextGenerationSettings);            var oneFontWidth = stepText.preferredWidth / block.StepList[i].Desc.Length;            //rows 一行多少个            var rowNumber = rectObj.sizeDelta.x / oneFontWidth;            //一共几行            var rows = block.StepList[i].Desc.Length / (rowNumber);            var remainder = block.StepList[i].Desc.Length % (rowNumber);            if (remainder > 0)            {                rows += 1;            }            //想要的高度 = 一共几行* 一行的高度;            rectObj.sizeDelta = new Vector2(rectObj.sizeDelta.x, (rows * fHeight));


原创粉丝点击