怎么使用UGUI图文混排做聊天气泡,考虑到有些人没有这方面的经验,下面就给大家介绍下利用UGUI图文混排实现聊天气泡的方法,一起来看看吧。
这里有同学建议在做聊天气泡时,可以更改为一张图集对应多个Text,这样能节省资源,不过我突然想到每个Text一个图集,可以随时更换图集,这样表情图更丰富一些,于是我就先将现有的聊天demo改为了聊天气泡,于是一张图集对应多个Text的功能,只有下次更新,哈哈。
1.我更新了原来的表情文件,不过资源也来源网络

2.在图文三的时候,为了做动态表情,将索引改为了ID,这里我有将ID改为了name,代码的检测中只要包含了name的图片都会加在动态数组里
- #region 解析动画标签
- List<string> tempListName = new List<string>();
- for (int i = 0; i < m_spriteAsset.listSpriteInfor.Count; i++)
- {
-
- if (m_spriteAsset.listSpriteInfor[i].name.Contains(match.Groups[1].Value))
- {
- tempListName.Add(m_spriteAsset.listSpriteInfor[i].name);
- }
- }
- if (tempListName.Count > 0)
- {
- SpriteTagInfor[] tempArrayTag = new SpriteTagInfor[tempListName.Count];
- for (int i = 0; i < tempArrayTag.Length; i++)
- {
- tempArrayTag[i] = new SpriteTagInfor();
- tempArrayTag[i].name = tempListName[i];
- tempArrayTag[i].index = match.Index;
- tempArrayTag[i].size = new Vector2(float.Parse(match.Groups[2].Value) * float.Parse(match.Groups[3].Value), float.Parse(match.Groups[2].Value));
- tempArrayTag[i].Length = match.Length;
- }
- listTagInfor.Add(tempArrayTag[0]);
- m_AnimSpiteTag.Add(listTagInfor.Count - 1, tempArrayTag);
- m_AnimIndex.Add(listTagInfor.Count - 1);
- }
- endregion
3.于是我们就可以更新一下表情文件的命令,一个动态表情的名称,尽量规范,大概看一下我的命名

4.然后就可以开始制作聊天气泡了,聊天气泡主要的因素就在于Item的制作,这里顺便看一下文本的表情表用格式,其实跟之前也是一样的

5.检测到输入的时候,再不断的生成预设就ok啦,具体一些参数,看看脚本应该能理解,并不难,于是就没怎么写出注释
- float chatHeight = 10.0f;
- float PlayerHight = 64.0f;
- void ClickSendMessageBtn()
- {
- if (inputText.text.Trim() == null || inputText.text.Trim() == "")
- return;
-
- GameObject tempChatItem = Instantiate(goprefab) as GameObject;
- tempChatItem.transform.parent = goContent.transform;
- tempChatItem.transform.localScale = Vector3.one;
- InlieText tempChatText = tempChatItem.transform.FindChild("Text").GetComponent();
- tempChatText.text = inputText.text.Trim();
- if (tempChatText.preferredWidth + 20.0f < 105.0f)
- {
- tempChatItem.GetComponent().sizeDelta = new Vector2(105.0f, tempChatText.preferredHeight + 50.0f);
- }
- else if (tempChatText.preferredWidth + 20.0f > tempChatText.rectTransform.sizeDelta.x)
- {
- tempChatItem.GetComponent().sizeDelta = new Vector2(tempChatText.rectTransform.sizeDelta.x + 20.0f, tempChatText.preferredHeight + 50.0f);
- }
- else
- {
- tempChatItem.GetComponent().sizeDelta = new Vector2(tempChatText.preferredWidth + 20.0f, tempChatText.preferredHeight + 50.0f);
- }
-
- tempChatItem.SetActive(true);
- tempChatText.SetVerticesDirty();
- tempChatItem.GetComponent().anchoredPosition = new Vector3(-10.0f, -chatHeight);
- chatHeight += tempChatText.preferredHeight + 50.0f + PlayerHight + 10.0f;
- if (chatHeight > goContent.GetComponent().sizeDelta.y)
- {
- goContent.GetComponent().sizeDelta = new Vector2(goContent.GetComponent().sizeDelta.x, chatHeight);
- }
- while (scrollbarVertical.value > 0.01f)
- {
- scrollbarVertical.value = 0.0f;
- }
- inputText.text = "";
- }
6.最后看一下效果截图,怕动态加载不出,多放一张静态图片:
