基于这篇:
zyf2533 - Unity 超链接 Text
修正了一些bug,额外支持了下划线以及自定义颜色。

/*https://blog.csdn.net/zyf2533/article/details/122703640*/using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.EventSystems;
//using UnityEngine.UI;namespace UnityEngine.UI
{[AddComponentMenu("UI/UIHyperlinkText")]/// <summary>/// eg:/// 获得了:<a href="Tip#1102201">先锋盾合成卷轴</a> /// </summary>public class UIHyperlinkText : Text, IPointerClickHandler{/// <summary>/// 超链接信息类/// </summary>private class HyperlinkInfo{//起始Indexpublic int StartIndex;//结束Indexpublic int EndIndex;//内容public string RefValue;public string InnerValue;//包围框public List<Rect> BoxList = new List<Rect>();}#region 私有变量//超链接正则private static Regex hrefRegex = new Regex(@"<a href=([^>\n\s]+)>(.*?)(</a>)", RegexOptions.Singleline);//颜色正则private static Regex colorRegex = new Regex(@"<color=([^>\n\s]+)>(.*?)(</color>)", RegexOptions.Singleline);private static Regex colorPreRegex = new Regex(@"<color=([^>\n\s]+)>", RegexOptions.Singleline);private static Regex colorEndRegex = new Regex(@"</color>", RegexOptions.Singleline);//超链接信息列表private List<HyperlinkInfo> hyperlinkInfoList = new List<HyperlinkInfo>();private static Action<string, string> clickCallback = null;private static Color innerTextColor = Color.blue;#endregion#region 公有变量#endregion#region 生命周期protected override void OnPopulateMesh(VertexHelper toFill){base.OnPopulateMesh(toFill);InitHyperlinkInfo();InitHyperlinkBox(toFill);DrawUnderLine(toFill);}#endregion#region 公有方法#endregion#region 动作public void OnPointerClick(PointerEventData eventData){Vector2 localPoint;RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, eventData.position, eventData.pressEventCamera, out localPoint);foreach (HyperlinkInfo hyperlinkInfo in hyperlinkInfoList){var boxeList = hyperlinkInfo.BoxList;for (var i = 0; i < boxeList.Count; ++i){if (boxeList[i].Contains(localPoint)){if (clickCallback != null){clickCallback(hyperlinkInfo.RefValue, hyperlinkInfo.InnerValue);}return;}}}}public static void RegisterClickCallback(Action<string, string> callback, string innerColor){ clickCallback = callback;if (!innerColor.StartsWith("#")){innerColor = "#" + innerColor;}Color nowColor;ColorUtility.TryParseHtmlString(innerColor, out nowColor);innerTextColor = nowColor;}#endregion#region 私有方法/// <summary>/// 初始化连接信息/// </summary>private void InitHyperlinkInfo(){GetOutputText(text);}/// <summary>/// 初始化连接包围框/// </summary>/// <param name="toFill"></param>private void InitHyperlinkBox(VertexHelper toFill){UIVertex vert = new UIVertex();// 处理超链接包围框foreach (var hrefInfo in hyperlinkInfoList){hrefInfo.BoxList.Clear();//一个字符是四个顶点,所以Index要乘以4int startVertex = hrefInfo.StartIndex * 4;int endVertex = hrefInfo.EndIndex * 4;if (startVertex >= toFill.currentVertCount){continue;}// 将超链接里面的文本顶点索引坐标加入到包围框toFill.PopulateUIVertex(ref vert, startVertex);var pos = vert.position;var bounds = new Bounds(pos, Vector3.zero);for (int i = startVertex; i < endVertex; i++){if (i >= toFill.currentVertCount){break;}toFill.PopulateUIVertex(ref vert, i);//toFill.SetUIVertex(vert, i);pos = vert.position;bool needEncapsulate = true;if ((i - startVertex) % 4 == 0){if (i < 4) continue;UIVertex lastV = new UIVertex();toFill.PopulateUIVertex(ref lastV, i - 4);var lastPos = lastV.position;if (pos.x < lastPos.x && pos.y < lastPos.y) // 换行重新添加包围框{hrefInfo.BoxList.Add(new Rect(bounds.min, bounds.size));bounds = new Bounds(pos, Vector3.zero);needEncapsulate = false;}}if (needEncapsulate){bounds.Encapsulate(pos); // 扩展包围框}}hrefInfo.BoxList.Add(new Rect(bounds.min, bounds.size));}}private void DrawUnderLine(VertexHelper vh){foreach (var link in hyperlinkInfoList){foreach (var rect in link.BoxList){float height = rect.height;// 左下var pos1 = new Vector3(rect.min.x, rect.min.y, 0);// 右下var pos2 = new Vector3(rect.max.x, rect.max.y, 0) - new Vector3(0, height, 0);MeshUnderLine(vh, pos1, pos2);}}}private void MeshUnderLine(VertexHelper vh, Vector2 startPos, Vector2 endPos){            Vector2 extents = rectTransform.rect.size;var setting = GetGenerationSettings(extents);TextGenerator underlineText = new TextGenerator();underlineText.Populate(" ̄", setting);IList<UIVertex> lineVer = underlineText.verts; //" ̄"的的顶点数组Vector3[] pos = new Vector3[4];pos[0] = startPos + new Vector2(-8, 0);pos[3] = startPos + new Vector2(-8, -4f);pos[2] = endPos + new Vector2(8, -4f);pos[1] = endPos + new Vector2(8, 0);if (lineVer.Count == 4){UIVertex[] tempVerts = new UIVertex[4];for (int i = 0; i < 4; i++){tempVerts[i] = lineVer[i];tempVerts[i].color = Color.white;tempVerts[i].position = pos[i];tempVerts[i].uv0 = lineVer[i].uv0;tempVerts[i].uv1 = lineVer[i].uv1;tempVerts[i].uv2 = lineVer[i].uv2;tempVerts[i].uv3 = lineVer[i].uv3;}vh.AddUIVertexQuad(tempVerts);}}/// <summary>/// 获取超链接解析后的最后输出文本/// </summary>/// <returns></returns>private string GetOutputText(string outputText){StringBuilder stringBuilder = new StringBuilder();hyperlinkInfoList.Clear();int strIndex = 0;foreach (Match match in hrefRegex.Matches(outputText)){//Debug.Log(match.Value);string appendStr = outputText.Substring(strIndex, match.Index - strIndex);//空格和回车没有顶点渲染,所以要去掉appendStr = appendStr.Replace(" ", "");appendStr = appendStr.Replace("\n", "");appendStr = RichStringFilter(appendStr);stringBuilder.Append(appendStr);int startIndex = stringBuilder.Length;//第一个是连接url,第二个是连接文本,跳转用url,计算index用文本Group urlGroup = match.Groups[1];Group titleGroup = match.Groups[2];//如果有Color语法嵌套,则还要继续扒,直到把最终文本扒出来Match colorMatch = colorRegex.Match(titleGroup.Value);if (colorMatch.Groups.Count > 3){titleGroup = colorMatch.Groups[2];}var inner = titleGroup.Value;inner = inner.Replace(" ", "");inner = inner.Replace("\n", "");stringBuilder.Append(inner);HyperlinkInfo hyperlinkInfo = new HyperlinkInfo{StartIndex = startIndex,EndIndex = (startIndex + inner.Length),RefValue = urlGroup.Value,InnerValue = titleGroup.Value,};strIndex = match.Index + match.Length;hyperlinkInfoList.Add(hyperlinkInfo);}stringBuilder.Append(outputText.Substring(strIndex, outputText.Length - strIndex));return stringBuilder.ToString();}private string RichStringFilter(string outputText){outputText = colorPreRegex.Replace(outputText, "");outputText = colorEndRegex.Replace(outputText, "");return outputText;}#endregion/// <summary>/// 添加可视包围框(测试用方法)/// </summary>private void AddVisibleBound(){int index = 0;foreach (Transform item in this.gameObject.transform.transform){Destroy(item.gameObject);}foreach (var hyperLinkInfo in hyperlinkInfoList){Color color = new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), 0.2f);index++;foreach (Rect rect in hyperLinkInfo.BoxList){GameObject gameObject = new GameObject();gameObject.name = string.Format("GOBoundBox[{0}]", hyperLinkInfo.InnerValue);gameObject.transform.SetParent(this.gameObject.transform);RectTransform rectTransform = gameObject.AddComponent<RectTransform>();rectTransform.sizeDelta = rect.size;rectTransform.localPosition = new Vector3(rect.position.x + rect.size.x / 2, rect.position.y + rect.size.y / 2, 0);Image image = gameObject.AddComponent<Image>();image.color = color;image.raycastTarget = false;}}}}
}

Unity超链接:支持点击事件,下划线以及自定义颜色相关推荐

  1. 微信小程序点击更改样式-点击获得下划线

    微信小程序点击更改样式-点击获得下划线 <view class="container"> <scroll-view class='headerBox' scrol ...

  2. div html 下边加横线_css字体下边横线 html超链接更改颜色和去掉下划线

    怎样用CSS样式在文字下面加下划线 一般有两种方法: 一.通过CSS下划线代码:text-decoration:underline来设置文字下划线. 实例演示如下: 实例代码如下: 此时页面效果如下: ...

  3. [安卓开发]弹幕滚幕效果自定义View之BarrageView|支持点击事件|隐藏不滞留|颜色随机|大小速度范围随机

    安卓弹幕滚幕效果自定义View之BarrageView|支持点击事件|隐藏不滞留|颜色随机|大小速度范围随机 1.简介 项目地址: https://github.com/tpnet/BarrageVi ...

  4. Unity UGUI图文混排(七) -- 下划线

    之前更新超链接的时候,忘了搭配实现一个下划线的功能,这篇文章就是来补上这一个功能,时间有点长,一方面没有很好的思路,一方面也没多少时间. 先在网上收集了一下下划线的实现操作,一种是在文本下再创建一个文 ...

  5. php a标签设置颜色,css超链接锚文本A标签下划线颜色改变

    css a超链接下划线设置装备摆设必要色采,鼠标悬停超链接翰墨字体上时下划线颜色窜改,字体色调波动 下划线样式: text-decoration:underline 下划线text-decoratio ...

  6. android span 下划线,Android TextView实现部分文字(超链接/Span)点击事件、变色、去除下划线...

    马上8月结束了,深海决定写点东西分享给大家,祝各位程序猿身体健康万事如意. 废话不多说,直接上图: 如图中蓝色文字的效果,需求如下: 1,点击跳转到另一个页面 2.去除下划线 3.颜色自定义 第一步: ...

  7. Jquery为DIV添加点击事件,Jquery为a标签超链接添加点击事件

    Js代码   <div>1</div> <div>2</div> <div>3</div> <div>4</d ...

  8. 前端<a>标签超链接,触发点击事件后弹出about:blank#blocked页

    一.问题描述 今天碰到一个特别奇怪的问题,我在点击一个超链接按钮后,会弹出一个about:blank#blocked页,原页面后续逻辑也会继续走下去,难受的点就是为什么会弹出这么一个页面. 二.问题分 ...

  9. php点击事件下一页,点击上一页下一页信息没有更新

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 代码如下: $conn= mysql_connect("localhost","root", "duol ...

最新文章

  1. 倒置函数reverse的用法
  2. python打开一个文件-python,一读取文件open()
  3. Android中代码运行指定的Apk
  4. 做好数据再利用,让企业数据价值发挥最大
  5. Shell--cut用法
  6. [leetcode] 108.有序数组转换为二叉搜索树
  7. scanf中的%[^\n]%*c格式
  8. 为什么有些语言会比别的快?
  9. 移动端拖拽排序 html,移动端拖拽排序
  10. 小白兔想的飞鸽传书(173dmba)安卓版
  11. TensorFlow HOWTO 1.2 LASSO、岭和 Elastic Net
  12. python读取文件名有中文_[请教]python的中文文件名处理
  13. 30幅精美的Photoshop三维字体作品欣赏及教程
  14. SpringBoot 生产中 16 条最佳实践
  15. MATLAB导数计算
  16. 知途云仓2.0 淘宝礼品一件代发php源码
  17. 秦牧鸿蒙之体有什么用,第一五一二章 鸿蒙元气
  18. 室内定位技术及机场方案建议
  19. XM 玻璃钢一体化泵站特点及使用寿命
  20. mysql定时任务,每天凌晨1点执行

热门文章

  1. Reporting报表开发知识汇总[个人原创]
  2. Docker(2) 安全加密,habor仓库和Docker网络
  3. 企业—habor docker镜像仓库的搭建
  4. CBOW(Continous Bag of Words)模型学习(2020-08-19)
  5. vue移动端用什么数据可视化插件_vue框架大屏可视化
  6. c/c++静态变量和静态函数
  7. OpenKruise :SidecarSet 助力 Mesh 容器热升级,TCP的三次握手、四次挥手
  8. vue项目屏幕自适应_vue项目自适应屏幕和浏览器
  9. 第43届ACM icpc亚洲区域赛焦作站感想
  10. 2018亚洲区域赛焦作站参赛总结