在unity的界面显示文字的时候,会出现字符串超出给定的范围的情况,比如本来设定的是显示5个字符串,但是由于某种原因,字符串长度变成了10,这样显示就会出现几种异常的情况:
- 如果加了ContentSizeFilter,并且设置了相应的选项的时候,有可能会出现自动换行,然后Text就会变高,这样显示就不好看;
- 如果没有添加任何控制Text组件的控制器,那么会莫名的丢掉多出来的字符串。
一般会将多出的字符串截掉,然后用...去替代。
首先想到的是直接根据字符串长度去截取,但是效果不是很理想,因为不同的字符,渲染的宽度不一样,这样就会造成即便截取了也会达不到效果,所以后来想到根据字符串的宽度来截取替代。
参考:http://blog.csdn.net/madcloudsong/article/details/54670045
核心部分代码:
Font myFont = text.font;
myFont.RequestCharactersInTexture(message, text.fontSize, text.fontStyle);
CharacterInfo characterInfo = new CharacterInfo();
char[] arr = message.ToCharArray();
foreach (char c in arr)
{
myFont.GetCharacterInfo(c, out characterInfo, text.fontSize);
totalLength += characterInfo.advance;
}
使用:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TextController :MonoBehaviour
{
public Text text;
private string suffix = "。。。";
int suffixLength = 0;
private string textToShow = "kdjfaliejlkfjlaisdjfklejfiasldkfj;ailjelkfjalskdvkljalkdjfielkjflksdfsdfa";
private string textToShow2 = "wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww";
private string textToShow3 = "我咖啡机客队 罚阿里会计法拉克京东方IE了拉进来打开房间啦看到逻辑拉克减肥的拉科技付款啦";
// Use this for initialization
void Start()
{
Init();
}
// Update is called once per frame
void Update()
{
}
public void ShowText()
{
text.text = StripLengthWithSuffix(textToShow3);
}
private void Init()
{
suffixLength = CalculateLengthOfText(suffix);
Debug.LogFormat("suffix length: {0}", suffixLength);
}
private string StripLengthWithSuffix(string input, int maxWidth = 460)
{
int len = CalculateLengthOfText(input);
Debug.LogFormat("input total length = {0}", len);
if(len > maxWidth)
{
return StripLength(input, maxWidth - suffixLength) + suffix;
}
else
{
return input;
}
}
private string StripLength(string input, int maxWidth = 460)
{
int totalLength = 0;
Font myFont = text.font;
myFont.RequestCharactersInTexture(input, text.fontSize, text.fontStyle);
CharacterInfo characterInfo = new CharacterInfo();
char[] arr = input.ToCharArray();
int i = 0;
foreach(char c in arr)
{
myFont.GetCharacterInfo(c, out characterInfo, text.fontSize);
int newLength = totalLength + characterInfo.advance;
if(newLength > maxWidth)
{
Debug.LogFormat("new length: {0} - total length: {1}", newLength, totalLength);
if(Mathf.Abs(newLength - maxWidth) > Mathf.Abs(maxWidth - totalLength))
{
break;
}
else
{
totalLength = newLength;
i++;
break;
}
}
totalLength += characterInfo.advance;
i++;
}
Debug.LogFormat("total length: {0}", totalLength);
return input.Substring(0, i);
}
private int CalculateLengthOfText(string message)
{
int totalLength = 0;
Font myFont = text.font;
myFont.RequestCharactersInTexture(message, text.fontSize, text.fontStyle);
CharacterInfo characterInfo = new CharacterInfo();
char[] arr = message.ToCharArray();
foreach(char c in arr)
{
myFont.GetCharacterInfo(c, out characterInfo, text.fontSize);
totalLength += characterInfo.advance;
}
return totalLength;
}
}
结果: