UGUI_Text的顯示

SendSi發表於2017-12-23

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
    }

相關文章