UITextHref.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using UnityEngine;
  6. using UnityEngine.Events;
  7. using UnityEngine.EventSystems;
  8. using UnityEngine.UI;
  9. public class UITextHref : Text, IPointerClickHandler
  10. {
  11. /// <summary>
  12. /// 图片池
  13. /// </summary>
  14. readonly List<Image> m_ImagesPool = new List<Image>();
  15. /// <summary>
  16. /// 图片的最后一个顶点的索引
  17. /// </summary>
  18. readonly List<int> m_ImagesVertexIndex = new List<int>();
  19. /// <summary>
  20. /// 超链接信息列表
  21. /// </summary>
  22. readonly List<HrefInfo> m_HrefInfos = new List<HrefInfo>();
  23. /// <summary>
  24. /// 解析完最终的文本
  25. /// </summary>
  26. string m_OutputText;
  27. bool clean = false;
  28. bool rebuilding = false;
  29. bool textDirty = false;
  30. /// <summary>
  31. /// 文本构造器
  32. /// </summary>
  33. readonly StringBuilder s_TextBuilder = new StringBuilder();
  34. /// <summary>
  35. /// 正则取出所需要的属性
  36. /// </summary>
  37. static readonly Regex s_Regex = new Regex(@"<quad name=(.+?) size=(\d*\.?\d+%?) width=(\d*\.?\d+%?) />", RegexOptions.Singleline);
  38. /// <summary>
  39. /// 超链接正则
  40. /// </summary>
  41. static readonly Regex s_HrefRegex = new Regex(@"<a href=([^>\n\s]+)>(.*?)(</a>)", RegexOptions.Singleline);
  42. /// <summary>
  43. /// 超链接点击事件
  44. /// </summary>
  45. public HrefClickEvent onHrefClick
  46. {
  47. get { return m_OnHrefClick; }
  48. set { m_OnHrefClick = value; }
  49. }
  50. [Serializable]
  51. public class HrefClickEvent : UnityEvent<string> { }
  52. [SerializeField]
  53. private HrefClickEvent m_OnHrefClick = new HrefClickEvent();
  54. /// <summary>
  55. /// 点击事件检测是否点击到超链接文本
  56. /// </summary>
  57. /// <param name="eventData"></param>
  58. public void OnPointerClick(PointerEventData eventData)
  59. {
  60. Vector2 lp = Vector2.zero;
  61. RectTransformUtility.ScreenPointToLocalPointInRectangle(
  62. rectTransform, eventData.position, eventData.pressEventCamera, out lp);
  63. foreach (var hrefInfo in m_HrefInfos)
  64. {
  65. var boxes = hrefInfo.boxes;
  66. for (var i = 0; i < boxes.Count; ++i)
  67. {
  68. if (boxes[i].Contains(lp))
  69. {
  70. m_OnHrefClick.Invoke(hrefInfo.name);
  71. return;
  72. }
  73. }
  74. }
  75. }
  76. public void SetText(string content)
  77. {
  78. text = content;
  79. if (text.Contains("<quad") && clean)
  80. textDirty = true;
  81. }
  82. /// <summary>
  83. /// 清理数据
  84. /// </summary>
  85. public void Clear()
  86. {
  87. clean = true;
  88. text = "";
  89. for(int idx = rectTransform.childCount- 1;idx >=0;idx--)
  90. GameObject.DestroyObject(rectTransform.GetChild(idx).gameObject);
  91. m_ImagesPool.Clear();
  92. m_ImagesVertexIndex.Clear();
  93. m_HrefInfos.Clear();
  94. s_TextBuilder.Remove(0, s_TextBuilder.Length);
  95. }
  96. float checkTime = 0;
  97. void LateUpdate()
  98. {
  99. if(textDirty && !rebuilding)
  100. {
  101. enabled = false;
  102. textDirty = false;
  103. enabled = true;
  104. }
  105. if (!textDirty && !rebuilding && (Time.time - checkTime) > 0.5f && !CheckImage())
  106. {
  107. enabled = false;
  108. checkTime = Time.time;
  109. enabled = true;
  110. }
  111. }
  112. public override void SetVerticesDirty()
  113. {
  114. base.SetVerticesDirty();
  115. UpdateQuadImage();
  116. }
  117. protected override void OnPopulateMesh(VertexHelper toFill)
  118. {
  119. var orignText = m_Text;
  120. m_Text = m_OutputText;
  121. base.OnPopulateMesh(toFill);
  122. m_Text = orignText;
  123. rebuilding = true;
  124. UIVertex vert = new UIVertex();
  125. for (var i = 0; i < m_ImagesVertexIndex.Count; i++)
  126. {
  127. var endIndex = m_ImagesVertexIndex[i];
  128. var rt = m_ImagesPool[i].rectTransform;
  129. if (rt == null) continue;
  130. var size = rt.sizeDelta;
  131. if (endIndex < toFill.currentVertCount)
  132. {
  133. toFill.PopulateUIVertex(ref vert, endIndex);
  134. float anchX = vert.position.x;
  135. float anchY = vert.position.y + size.y / 2;
  136. rt.anchoredPosition = new Vector2(anchX,anchY);
  137. // 抹掉左下角的小黑点
  138. toFill.PopulateUIVertex(ref vert, endIndex - 3);
  139. var pos = vert.position;
  140. for (int j = endIndex, m = endIndex - 3; j > m; j--)
  141. {
  142. toFill.PopulateUIVertex(ref vert, endIndex);
  143. vert.position = pos;
  144. toFill.SetUIVertex(vert, j);
  145. }
  146. }
  147. }
  148. if (m_ImagesVertexIndex.Count != 0)
  149. {
  150. m_ImagesVertexIndex.Clear();
  151. }
  152. // 处理超链接包围框
  153. foreach (var hrefInfo in m_HrefInfos)
  154. {
  155. hrefInfo.boxes.Clear();
  156. if (hrefInfo.startIndex >= toFill.currentVertCount)
  157. {
  158. continue;
  159. }
  160. // 将超链接里面的文本顶点索引坐标加入到包围框
  161. toFill.PopulateUIVertex(ref vert, hrefInfo.startIndex);
  162. var pos = vert.position;
  163. var bounds = new Bounds(pos, Vector3.zero);
  164. for (int i = hrefInfo.startIndex, m = hrefInfo.endIndex; i < m; i++)
  165. {
  166. if (i >= toFill.currentVertCount)
  167. {
  168. break;
  169. }
  170. toFill.PopulateUIVertex(ref vert, i);
  171. pos = vert.position;
  172. if (pos.x < bounds.min.x) // 换行重新添加包围框
  173. {
  174. hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
  175. bounds = new Bounds(pos, Vector3.zero);
  176. }
  177. else
  178. {
  179. bounds.Encapsulate(pos); // 扩展包围框
  180. }
  181. }
  182. hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
  183. }
  184. rebuilding = false;
  185. }
  186. protected void UpdateQuadImage()
  187. {
  188. #if UNITY_EDITOR
  189. if (UnityEditor.PrefabUtility.GetPrefabType(this) == UnityEditor.PrefabType.Prefab)
  190. {
  191. return;
  192. }
  193. #endif
  194. m_OutputText = GetOutputText();
  195. m_ImagesVertexIndex.Clear();
  196. foreach (Match match in s_Regex.Matches(m_OutputText))
  197. {
  198. var picIndex = match.Index;
  199. var endIndex = picIndex * 4 + 3;
  200. m_ImagesVertexIndex.Add(endIndex);
  201. m_ImagesPool.RemoveAll(image => image == null);
  202. if (m_ImagesPool.Count == 0)
  203. {
  204. GetComponentsInChildren<Image>(m_ImagesPool);
  205. }
  206. if (m_ImagesVertexIndex.Count > m_ImagesPool.Count)
  207. {
  208. var resources = new DefaultControls.Resources();
  209. var go = DefaultControls.CreateImage(resources);
  210. go.layer = gameObject.layer;
  211. var rt = go.transform as RectTransform;
  212. if (rt)
  213. {
  214. rt.anchorMin = rectTransform.anchorMin;
  215. rt.anchorMax = rectTransform.anchorMax;
  216. rt.pivot = rectTransform.pivot;
  217. rt.SetParent(rectTransform);
  218. rt.localPosition = Vector3.zero;
  219. rt.localRotation = Quaternion.identity;
  220. rt.localScale = Vector3.one;
  221. }
  222. m_ImagesPool.Add(go.GetComponent<Image>());
  223. }
  224. var spriteName = match.Groups[1].Value;
  225. var size = float.Parse(match.Groups[2].Value);
  226. var img = m_ImagesPool[m_ImagesVertexIndex.Count - 1];
  227. if (img.sprite == null || img.sprite.name != spriteName)
  228. {
  229. //img.sprite = UIUtility.LoadChatFace(spriteName);
  230. }
  231. img.rectTransform.sizeDelta = new Vector2(size, size);
  232. img.enabled = true;
  233. }
  234. for (var i = m_ImagesVertexIndex.Count; i < m_ImagesPool.Count; i++)
  235. {
  236. if (m_ImagesPool[i])
  237. {
  238. m_ImagesPool[i].enabled = false;
  239. }
  240. }
  241. }
  242. /// <summary>
  243. /// 获取超链接解析后的最后输出文本
  244. /// </summary>
  245. /// <returns></returns>
  246. protected string GetOutputText()
  247. {
  248. s_TextBuilder.Length = 0;
  249. m_HrefInfos.Clear();
  250. var indexText = 0;
  251. foreach (Match match in s_HrefRegex.Matches(text))
  252. {
  253. s_TextBuilder.Append(text.Substring(indexText, match.Index - indexText));
  254. s_TextBuilder.Append("<color=blue>"); // 超链接颜色
  255. var group = match.Groups[1];
  256. var hrefInfo = new HrefInfo
  257. {
  258. startIndex = s_TextBuilder.Length * 4, // 超链接里的文本起始顶点索引
  259. endIndex = (s_TextBuilder.Length + match.Groups[2].Length - 1) * 4 + 3,
  260. name = group.Value
  261. };
  262. m_HrefInfos.Add(hrefInfo);
  263. s_TextBuilder.Append(match.Groups[2].Value);
  264. s_TextBuilder.Append("</color>");
  265. indexText = match.Index + match.Length;
  266. }
  267. s_TextBuilder.Append(text.Substring(indexText, text.Length - indexText));
  268. return s_TextBuilder.ToString();
  269. }
  270. /// <summary>
  271. /// 超链接信息类
  272. /// </summary>
  273. private class HrefInfo
  274. {
  275. public int startIndex;
  276. public int endIndex;
  277. public string name;
  278. public readonly List<Rect> boxes = new List<Rect>();
  279. }
  280. /// <summary>
  281. /// 计算文本可能占用的宽度
  282. /// </summary>
  283. /// <param name="content"></param>
  284. /// <returns></returns>
  285. public float CalcWidth(string content)
  286. {
  287. string temp = content;
  288. float width = 0;
  289. foreach (var match in s_Regex.Matches(temp))
  290. {
  291. temp = temp.Replace(match.ToString(), "/表情");
  292. }
  293. font.RequestCharactersInTexture(temp, font.fontSize, FontStyle.Normal);
  294. CharacterInfo characterInfo;
  295. for (int idx = 0; idx < temp.Length; idx++)
  296. {
  297. font.GetCharacterInfo(temp[idx], out characterInfo, font.fontSize);
  298. width += characterInfo.advance;
  299. }
  300. return width;
  301. }
  302. /// <summary>
  303. /// 核对图片是否合法
  304. /// </summary>
  305. /// <returns></returns>
  306. bool CheckImage()
  307. {
  308. if (rectTransform.childCount == 0) return true;
  309. for (int idx = 0; idx < rectTransform.childCount; idx++)
  310. {
  311. Transform trans = rectTransform.GetChild(idx);
  312. if (trans.localPosition.x < 0) return false;
  313. }
  314. return true;
  315. }
  316. }