如何在Unity中实现聊天文本,控制Text文本长度,自动换行

    


 
    public Image image;
    public string text = "This is a chat that wraps itself";
    public float with = 200;
    private Text mailText;
    RectTransform rect;

    RectTransform imgRect;
    void Start()
    {
        mailText = GetComponent<Text>();
        rect = GetComponent<RectTransform>();

        imgRect = image.GetComponent<RectTransform>();
    }
    void Update()
    {
        float curWith = 0;
        mailText.text = text;
        if (mailText.preferredWidth < with)
            curWith = mailText.preferredWidth;
        else
            curWith = with;
        rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, curWith);
        rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, mailText.preferredHeight);

        imgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, curWith);
        imgRect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, mailText.preferredHeight);
    }

RectTransform中有个方法SetSizeWithCurrentAnchors,可以设置这个RectTransform的长度或者宽度。

大于你要的长度时,设置成最大长度,否则设置成当前长度。

imgRect是用来设置聊天背景图片的。

 

这时会发现有一个问题,当内容不足时,不是向左对齐的 ,而是居中缩放。

这是因为锚点不对,我们停止运行,把文本和背景的锚点都这是到左边居中

再运行就好了。

 

 

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值