UGUI_Text的显示

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
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值