Unity 图文混排超链接图片均可点击

1.在其他博主的基础上,增加了图片可以点击的功能,因为我临时遇到了这个需求,这应该是图文混排的终极版本了吧,如果以后图文混排相关功能还有增加的话,我再临时更新此篇文章吧!希望可以帮到拥有同样需求的你们,谢谢!

2.此代码为图文混排代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;

/// 
/// 文本控件,支持超链接、图片
/// 
[AddComponentMenu("UI/LinkImageText", 10)]
public class LinkImageText : RichText, IPointerClickHandler
{
    /// 
    /// 解析完最终的文本
    /// 
    private string m_OutputText;

    /// 
    /// 图片池
    /// 
    protected readonly List m_ImagesPool = new List();

    /// 
    /// 图片的最后一个顶点的索引
    /// 
    private readonly List<int> m_ImagesVertexIndex = new List<int>();


    /// 
    /// 超链接信息列表
    /// 
    private readonly List m_HrefInfos = new List();
    /// 
    /// 图片信息列表
    /// 
    private readonly List m_ImageInfos = new List();
    /// 
    /// 文本构造器
    /// 
    protected static readonly StringBuilder s_TextBuilder = new StringBuilder();

    [Serializable]
    public class HrefClickEvent : UnityEvent<string> { }

    [SerializeField]
    private HrefClickEvent m_OnHrefClick = new HrefClickEvent();

    /// 
    /// 超链接点击事件
    /// 
    public HrefClickEvent onHrefClick
    {
        get { return m_OnHrefClick; }
        set { m_OnHrefClick = value; }
    }


    [Serializable]
    public class ImageClickEvent : UnityEvent<string> { }

    [SerializeField]
    private ImageClickEvent m_OnImageClick = new ImageClickEvent();

    /// 
    /// 图片点击事件
    /// 
    public ImageClickEvent onImageClick
    {
        get { return m_OnImageClick; }
        set { m_OnImageClick = value; }
    }

    /// 
    /// 正则取出所需要的属性
    /// 
    private static readonly Regex s_ImageRegex =
        new Regex(@"\[quad (.*?)\](\[-\])", RegexOptions.Singleline);
    //new Regex(@"", RegexOptions.Singleline);
    private static readonly Regex s_ImageRegex1 =
        new Regex(@"", RegexOptions.Singleline);
    /// 
    /// 超链接正则
    /// 
    private static readonly Regex s_HrefRegex =
        new Regex(@"\[a href=(.*?)\](.*?)(\[-\])", RegexOptions.Singleline);

    //private string lastSetText = null;
    public override string text
    {
        get
        {
            base.text = s_ImageRegex.Replace(base.text, "");
            return base.text;
        }

    }

    /// 
    /// 加载精灵图片方法
    /// 
    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_ImageRegex1.Matches(m_OutputText))
        {
            var picIndex = match.Index;
            var endIndex = picIndex * 4 + 3;
            m_ImagesVertexIndex.Add(endIndex);

            m_ImagesPool.RemoveAll(image => image == null);
            if (m_ImagesPool.Count == 0)
            {
                GetComponentsInChildren(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());
            }

            var spriteName = match.Groups[1].Value;
            var size = float.Parse(match.Groups[2].Value);
            var id = match.Groups[5].Value;
            var img = m_ImagesPool[m_ImagesVertexIndex.Count - 1];
            if (img.sprite == null || img.sprite.name != spriteName)
            {
                //UI.UpdateSpriteImage(img, "", "");
                img.sprite = funLoadSprite != null ? funLoadSprite(spriteName) :
                    Resources.Load(spriteName);
            }
            img.rectTransform.sizeDelta = new Vector2(size, size);
            var ImageInfo = new ImageInfo
            {
                ImageName = spriteName,
                ImageSize = img.rectTransform.sizeDelta,
                ImageId = id
            };
            m_ImageInfos.Add(ImageInfo);
            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 = 0; 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 / 2, vert.position.y + size.y / 2);
                // 抹掉左下角的小黑点
                toFill.PopulateUIVertex(ref vert, endIndex - 3);
                var pos = vert.position;
                for (int j = endIndex, m = endIndex - 3; j > m; j--)
                {
                    toFill.PopulateUIVertex(ref vert, endIndex);
                    vert.position = pos;
                    toFill.SetUIVertex(vert, j);
                }
            }
        }

        if (m_ImagesVertexIndex.Count != 0)
        {
            m_ImagesVertexIndex.Clear();
        }
        //处理图片包围狂
        foreach (var imageInfo in m_ImageInfos)
        {
            imageInfo.ImageBoxes.Add(new Rect(new Vector2(vert.position.x, vert.position.y - imageInfo.ImageSize.y), imageInfo.ImageSize));
        }
        // 处理超链接包围框
        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));

        }



    }

    /// 
    /// 获取超链接解析后的最后输出文本
    /// 
    /// 
    protected virtual string GetOutputText(string outputText)
    {
        s_TextBuilder.Length = 0;
        m_HrefInfos.Clear();
        var indexText = 0;
        foreach (Match match in s_HrefRegex.Matches(outputText))
        {
            s_TextBuilder.Append(outputText.Substring(indexText, match.Index - indexText));
            s_TextBuilder.Append("");  // 超链接颜色

            var group = match.Groups[1];
            var hrefInfo = new HrefInfo
            {
                startIndex = s_TextBuilder.Length * 4, // 超链接里的文本起始顶点索引
                endIndex = (s_TextBuilder.Length + match.Groups[2].Length - 1) * 4 + 3,
                name = group.Value
            };
            m_HrefInfos.Add(hrefInfo);

            s_TextBuilder.Append(match.Groups[2].Value);
            s_TextBuilder.Append("");
            indexText = match.Index + match.Length;
        }
        s_TextBuilder.Append(outputText.Substring(indexText, outputText.Length - indexText));
        return s_TextBuilder.ToString();
    }

    /// 
    /// 点击事件检测是否点击到超链接文本或者图片
    /// 
    /// 
    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 = 0; i < boxes.Count; ++i)
            {
                if (boxes[i].Contains(lp))
                {
                    m_OnHrefClick.Invoke(hrefInfo.name);
                    return;
                }
            }
        }

        foreach (var imageInfo in m_ImageInfos)
        {
            var boxes = imageInfo.ImageBoxes;
            for (var i = 0; i < boxes.Count; ++i)
            {
                if (boxes[i].Contains(lp))
                {
                    if (imageInfo.ImageId != null && imageInfo.ImageId != "")
                    {
                        m_OnImageClick.Invoke(imageInfo.ImageId);
                        return;
                    }
                }

            }
        }

    }


    /// 
    /// 超链接信息类
    /// 
    private class HrefInfo
    {
        public int startIndex;

        public int endIndex;

        public string name;

        public readonly List boxes = new List();
    }
    /// 
    /// 图片信息类
    /// 
    private class ImageInfo
    {

        public string ImageName;

        public Vector2 ImageSize;

        public string ImageId;

        public readonly List ImageBoxes = new List();
    }
}

3.此代码为添加点击事件代码

using UnityEngine;

public class testHref : MonoBehaviour
{
    public LinkImageText textPic;

    void Awake()
    {
        textPic = GetComponent();
    }

    void OnEnable()
    {
        textPic.onHrefClick.AddListener(OnHrefClick);
        textPic.onImageClick.AddListener(OnHrefClick1);
    }

    void OnDisable()
    {
        textPic.onHrefClick.RemoveListener(OnHrefClick);
    }

    private void OnHrefClick(string hrefName)
    {
        Debug.Log("点击了 " + hrefName);
    }

    private void OnHrefClick1(string hrefName)
    {
        Debug.Log("点击了 " + hrefName);
    }

}

4.感谢您认真看完了此文章,如果有更好的方案可以分享出来,我们一起学习!

你可能感兴趣的:(unity3d)