using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI; /// <summary>
/// 文本控件,支持超链接、图片
/// </summary>
[AddComponentMenu("UI/Text_Pro", )]
public class Text_Pro : Text, IPointerClickHandler
{
/// <summary>
/// 解析完最终的文本
/// </summary>
private string m_OutputText; /// <summary>
/// 图片池
/// </summary>
protected readonly List<Image> m_ImagesPool = new List<Image>(); /// <summary>
/// 图片的最后一个顶点的索引
/// </summary>
private readonly List<int> m_ImagesVertexIndex = new List<int>(); /// <summary>
/// 超链接信息列表
/// </summary>
private readonly List<HrefInfo> m_HrefInfos = new List<HrefInfo>(); /// <summary>
/// 文本构造器
/// </summary>
protected static readonly StringBuilder s_TextBuilder = new StringBuilder(); [Serializable]
public class HrefClickEvent : UnityEvent<string> { } [SerializeField]
private HrefClickEvent m_OnHrefClick = new HrefClickEvent(); /// <summary>
/// 超链接点击事件
/// </summary>
public HrefClickEvent onHrefClick
{
get { return m_OnHrefClick; }
set { m_OnHrefClick = value; }
} /// <summary>
/// 正则-图片
/// </summary>
private static readonly Regex s_ImageRegex =
new Regex(@"<quad name=(.+?) size=(\d*\.?\d+%?) width=(\d*\.?\d+%?) />", RegexOptions.Singleline); /// <summary>
/// 正则-超链接
/// </summary>
private static readonly Regex s_HrefRegex =
new Regex(@"<a href=([^>\n\s]+)>(.*?)(</a>)", RegexOptions.Singleline); /// <summary>
/// 加载精灵图片方法
/// </summary>
public static Func<string, Sprite> funLoadSprite; public override void SetVerticesDirty()
{
base.SetVerticesDirty();
UpdateQuadImage();
} protected void UpdateQuadImage()
{
#if UNITY_EDITOR
if (UnityEditor.PrefabUtility.GetPrefabType(this) == UnityEditor.PrefabType.Prefab)
{
return;
}
#endif m_OutputText = GetOutputText(text);
m_ImagesVertexIndex.Clear();
foreach (Match match in s_ImageRegex.Matches(m_OutputText))
{
var picIndex = match.Index;
var endIndex = picIndex * + ;
m_ImagesVertexIndex.Add(endIndex); m_ImagesPool.RemoveAll(image => image == null);
if (m_ImagesPool.Count == )
{
GetComponentsInChildren<Image>(m_ImagesPool);
}
if (m_ImagesVertexIndex.Count > m_ImagesPool.Count)
{
var resources = new DefaultControls.Resources();
var go = DefaultControls.CreateImage(resources);
go.layer = gameObject.layer;
var rt = go.transform as RectTransform;
if (rt)
{
rt.SetParent(rectTransform);
rt.localPosition = Vector3.zero;
rt.localRotation = Quaternion.identity;
rt.localScale = Vector3.one;
}
m_ImagesPool.Add(go.GetComponent<Image>());
} var spriteName = match.Groups[].Value;
var size = float.Parse(match.Groups[].Value);
var img = m_ImagesPool[m_ImagesVertexIndex.Count - ];
if (img.sprite == null || img.sprite.name != spriteName)
{
img.sprite = funLoadSprite != null ? funLoadSprite(spriteName) :
Resources.Load<Sprite>(spriteName);
}
img.rectTransform.sizeDelta = new Vector2(size, size);
img.enabled = true;
} for (var i = m_ImagesVertexIndex.Count; i < m_ImagesPool.Count; i++)
{
if (m_ImagesPool[i])
{
m_ImagesPool[i].enabled = false;
}
}
} protected override void OnPopulateMesh(VertexHelper toFill)
{
var orignText = m_Text;
m_Text = m_OutputText;
base.OnPopulateMesh(toFill);
m_Text = orignText; UIVertex vert = new UIVertex();
for (var i = ; i < m_ImagesVertexIndex.Count; i++)
{
var endIndex = m_ImagesVertexIndex[i];
var rt = m_ImagesPool[i].rectTransform;
var size = rt.sizeDelta;
if (endIndex < toFill.currentVertCount)
{
toFill.PopulateUIVertex(ref vert, endIndex);
rt.anchoredPosition = new Vector2(vert.position.x + size.x / , vert.position.y + size.y / ); // 抹掉左下角的小黑点
toFill.PopulateUIVertex(ref vert, endIndex - );
var pos = vert.position;
for (int j = endIndex, m = endIndex - ; j > m; j--)
{
toFill.PopulateUIVertex(ref vert, endIndex);
vert.position = pos;
toFill.SetUIVertex(vert, j);
}
}
} if (m_ImagesVertexIndex.Count != )
{
m_ImagesVertexIndex.Clear();
} // 处理超链接包围框
foreach (var hrefInfo in m_HrefInfos)
{
hrefInfo.boxes.Clear();
if (hrefInfo.startIndex >= toFill.currentVertCount)
{
continue;
} // 将超链接里面的文本顶点索引坐标加入到包围框
toFill.PopulateUIVertex(ref vert, hrefInfo.startIndex);
var pos = vert.position;
var bounds = new Bounds(pos, Vector3.zero);
for (int i = hrefInfo.startIndex, m = hrefInfo.endIndex; i < m; i++)
{
if (i >= toFill.currentVertCount)
{
break;
} toFill.PopulateUIVertex(ref vert, i);
pos = vert.position;
if (pos.x < bounds.min.x) // 换行重新添加包围框
{
hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
bounds = new Bounds(pos, Vector3.zero);
}
else
{
bounds.Encapsulate(pos); // 扩展包围框
}
}
hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
}
} /// <summary>
/// 获取超链接解析后的最后输出文本
/// </summary>
/// <returns></returns>
protected virtual string GetOutputText(string outputText)
{
s_TextBuilder.Length = ;
m_HrefInfos.Clear();
var indexText = ;
foreach (Match match in s_HrefRegex.Matches(outputText))
{
s_TextBuilder.Append(outputText.Substring(indexText, match.Index - indexText));
s_TextBuilder.Append("<color=blue>"); // 超链接颜色 var group = match.Groups[];
var hrefInfo = new HrefInfo
{
startIndex = s_TextBuilder.Length * , // 超链接里的文本起始顶点索引
endIndex = (s_TextBuilder.Length + match.Groups[].Length - ) * + ,
name = group.Value
};
m_HrefInfos.Add(hrefInfo); s_TextBuilder.Append(match.Groups[].Value);
s_TextBuilder.Append("</color>");
indexText = match.Index + match.Length;
}
s_TextBuilder.Append(outputText.Substring(indexText, outputText.Length - indexText));
return s_TextBuilder.ToString();
} /// <summary>
/// 点击事件检测是否点击到超链接文本
/// </summary>
/// <param name="eventData"></param>
public void OnPointerClick(PointerEventData eventData)
{
Vector2 lp;
RectTransformUtility.ScreenPointToLocalPointInRectangle(
rectTransform, eventData.position, eventData.pressEventCamera, out lp); foreach (var hrefInfo in m_HrefInfos)
{
var boxes = hrefInfo.boxes;
for (var i = ; i < boxes.Count; ++i)
{
if (boxes[i].Contains(lp))
{
m_OnHrefClick.Invoke(hrefInfo.name);
return;
}
}
}
} /// <summary>
/// 超链接信息类
/// </summary>
private class HrefInfo
{
public int startIndex;
public int endIndex;
public string name;
public readonly List<Rect> boxes = new List<Rect>();
}
}

作者:无幻

原文:https://blog.csdn.net/akof1314/article/details/49077983

源码和示例地址:https://github.com/akof1314/uGUI_LinkImageText

转载 Unity Text 插入超链接的更多相关文章

  1. word-如何将文字设置为插入超链接

    前言 使用word有时候想要将文字部分设置为插入超链接,本文对此进行介绍. 操作步骤 1. 输入需要插入链接的文字部分: 2. 选中文字部分单击右键,点击超链接进行插入: 具体操作如下图所示: 参考 ...

  2. [转载]Sublime Text 3 搭建 React.js 开发环境

    [转载]Sublime Text 3 搭建 React.js 开发环境 Sublime有很强的自定义功能,插件库很庞大,针对新语言插件更新很快,配合使用可以快速搭建适配语言的开发环境. 1. babe ...

  3. (转载)Unity学习笔记:关于Dropdown的学习

    今天组长让我写一个界面,其中用到了下拉条,我的印象还停留在以前的NGUI有现成的组件,但是uGUI没有的那阶段,组长跟我说uGUI现在也有了,研究了一下,发现real方便哦,今天就来简单说一下用法吧. ...

  4. (转载)Sublime Text 3 快捷键大全

    选择类Ctrl+D 选中光标所占的文本,继续操作则会选中下一个相同的文本.Alt+F3 选中文本按下快捷键,即可一次性选择全部的相同文本进行同时编辑.举个栗子:快速选中并更改所有相同的变量名.函数名等 ...

  5. Unity 3D插入MySql中文无法显示问题

    使用Unity3D向mySql中插入数据,然后进入mySql查看数据库,吓我一跳中文全部乱码. 随后各种查阅资料,网站上给出解释,MySql应该使用utf8编码,查看我的mySql默认是使用utf8编 ...

  6. (转载)Unity 优化总结

    Unity 优化总结 2017-03-10 | 发布 大海明月  zengfeng75@qq.com  | 分类 Unity  | 标签 Unity  优化 相关文档 UGUI 降低填充率技巧两则 U ...

  7. 转载unity编辑器xml数据库插件

    unity编辑器xml数据库插件 注:9月9日更新,其中MyXML.cs中有一句代码写错,查找功能失误,文中已经修改! 注:9月1日更新说明:xml存储结构,因为在用xml之前不知道正规的xml数据结 ...

  8. (转载)Sumblime Text 2 常用插件以及安装方法

    [内容提要]使用Package Control组件在线安装更方便 安装Sublime Text 2插件的方法: 1.直接安装 安装Sublime text 2插件很方便,可以直接下载安装包解压缩到Pa ...

  9. [转载]Sublime Text 2 - 性感无比的代码编辑器!程序员必备神器!跨平台支持Win/Mac/Linux

    代码编辑器或者文本编辑器,对于程序员来说,就像剑与战士一样,谁都想拥有一把可以随心驾驭且锋利无比的宝剑,而每一位程序员,同样会去追求最适合自己的强大.灵活的编辑器,相信你和我一样,都不会例外. 我用过 ...

随机推荐

  1. ubuntu 使用旧式Gnome风格的菜单

    sudo apt-add-repository ppa:diesch/testing sudo apt-get update sudo apt-get install classicmenu-indi ...

  2. 了解cron以及使用cron定时备份MySQL

    cron是一个linux下的定时执行工具,可以在无需人工干预的情况下运行作业.由于Cron 是Linux的内置服务,但它不自动起来,可以用以下的方法启动.关闭这个服务: /sbin/service c ...

  3. GeForce GTX 1080 ti安装记录

    安装GeForce GTX 1080ti 安装GeForce GTX 1080ti,8+8pin需要全接,接4pin就开机显示器上会提示电源线没接完,将显示器线接在显卡上. 设置Win 10 pro ...

  4. pointcut 切面表达式 切入点表达式

    下面给出一些常见切入点表达式的例子. 任意公共方法的执行: execution(public * *(..)) 任何一个以“set”开始的方法的执行: execution(* set*(..)) Ac ...

  5. Linux 下执行Shell 脚本的方式

    Shell 脚本的执行方式通常有如下三种: (1)bash script-name 或者 sh script-name:(2)path/script-name或者./script-name:(3)so ...

  6. 可视化展示attention(seq2seq with attention in tensorflow)

    目前实现了基于tensorflow的支持的带attention的seq2seq.基于tf 1.0官网contrib路径下seq2seq 由于后续版本不再支持attention,迁移到melt并做了进一 ...

  7. [原]Jenkins(一)---我理解的jenkins是这样的(附全套PDF下载)

    /** * lihaibo * 文章内容都是根据自己工作情况实践得出. *版权声明:本博客欢迎转发,但请保留原作者信息! http://www.cnblogs.com/horizonli/p/5330 ...

  8. Cookiecutter: 更好的项目模板工具:(2)安装及基础使用

    安装 通过python包管理工具 命令行输入 $pip install cookiecutter 或者 # mac os经常会禁止用户全局安装python包 $pip install --user c ...

  9. HTML中的清除浮动的常用方法(转载)

    以下面的div为例: HTML: <div class="test"> <div class="test1"></div> ...

  10. java个人博客源码

    初入博客园,请各位多关照,来而不往非礼也. 如需要源码以及学习内容,qq:1397617269,我看到就回你们资源. 直接给链接: 链接:https://pan.baidu.com/s/1S_awtg ...