2.Unity经验:随文字个数变化的聊天气泡

Unity气泡文字控件实现
本文介绍了一个在Unity中实现动态调整大小的气泡文字控件的代码示例。该控件能够根据输入文本的长度自动调整其大小,确保文字完全显示。代码使用了InputField、Image和Text组件,并通过计算文本字符数量来动态修改气泡的宽度和高度。

1.效果图

2.代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class BubbleTextCtl : MonoBehaviour
{
    private InputField inputField;
    private Image bubbleImg;
    private Text bubbleText;

    // 这里不处理中英文情况
    private int charW = 20; // 一个字宽度
    private int charH = 26; // 一个字高度
    private int maxW = 200; // 最大宽度

    void Awake()
    {
        GameObject bubbleView = GameObject.Find("BubbleView");
        inputField = bubbleView.transform.Find("InputField").GetComponent<InputField>();
        bubbleImg = bubbleView.transform.Find("Icon/BubbleImg").GetComponent<Image>();
        bubbleText = bubbleView.transform.Find("Icon/BubbleImg/BubbleText").GetComponent<Text>();
        Button sendBtn = bubbleView.transform.Find("SendBtn").GetComponent<Button>();
        
        sendBtn.onClick.AddListener(OnSendBtnClick);
    }

    void OnSendBtnClick()
    {
        // 1.把输入框string赋值给气泡string
        string bubbleTextStr = inputField.text;
        // 2.计算bubbleTextStr的文字个数
        int strLen = bubbleTextStr.Length;
        decimal result = (decimal)strLen / 10;
        int num = Mathf.CeilToInt((float)result);

        // 3.清空输入框
        inputField.text = "";

        // 4.计算RectTransform的大小
        int wCount = num;
        int width = wCount > 1 ? maxW : charW * strLen;
        int height = wCount * charH;
        bubbleImg.rectTransform.sizeDelta = new Vector2(width, height);

        // 5.给气泡Text赋值
        bubbleText.text = bubbleTextStr;
    }
}

3.仓库地址

https://github.com/getker/BubbleText

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Kerven_HKW

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值