Text的显示,若内容长度过长显示(内容…)
若Text本来能容纳7个字的,7个字为正常字.但服务器往往取出来的字符串不定长…过长就显示6+…
/// <summary>
/// 昵称长度的显示 返回值(渣渣曾detail...:+20)
/// </summary>
public string GetUITextContent(Text uiTemp, string strTemp, float containerWidth)
{
if (strTemp == null) return "";
if (strTemp == "") return "";
Font font = uiTemp.font;
font.RequestCharactersInTexture(strTemp, uiTemp.fontSize, uiTemp.fontStyle);
CharacterInfo characterInfo;
float width = 0f;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
for (int i = 0; i < strTemp.Length; i++)
{
font.GetCharacterInfo(strTemp[i], out characterInfo, uiTemp.fontSize);
width += characterInfo.advance;
if (width < containerWidth)
{
sb.Append(strTemp[i]);
}
}
if (containerWidth > width)//本来能容纳
return sb.ToString();
else
return sb.Remove(sb.Length - 1, 1).Append("...").ToString();
}
/// <summary>
/// 昵称长度的显示 返回值(渣渣曾detail.....)
/// </summary>
public string GetUITextContent(Text uiTemp, string strTemp)
{
float containerWidth = uiTemp.GetComponent<RectTransform>().sizeDelta.x;//容器的width
return GetUITextContent(uiTemp, strTemp, containerWidth);
}
/// <summary>
/// 昵称长度的显示 原长度为(渣渣曾detail是姓曾的)显示为(渣渣曾detail...)
/// </summary>
public void SetUITextContent(Text uiTemp, string strTemp)
{
var str = GetUITextContent(uiTemp, strTemp);
uiTemp.text = str;
}
UGUI_Image长度跟随Text的内容而设定
public void SetImageText(string strTemp)
{
var tempText = this.msgItemPerfab.GetComponentInChildren<Text>();
Font font = tempText.font;
font.RequestCharactersInTexture(strTemp, tempText.fontSize, tempText.fontStyle);
CharacterInfo characterInfo;
float width = 0f;
for (int i = 0; i < strTemp.Length; i++)
{
font.GetCharacterInfo(strTemp[i], out characterInfo, tempText.fontSize);
width += characterInfo.advance;
}
//计算出长度
var tempTr = this.msgItemPerfab.GetComponent<RectTransform>();
tempTr.sizeDelta = new Vector2(width + 40, 40);
tempText.text = strTemp;
//UGUI 可以不写代码的....使用ContentSizeFitter,HorizontalLayoutGroup
}