国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

unity ugui text 超鏈接和下劃線,支持部分富文本格式

這篇具有很好參考價值的文章主要介紹了unity ugui text 超鏈接和下劃線,支持部分富文本格式。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

unity版本:2021.3.6f1
局限性:
1.測試發(fā)現(xiàn)不能使用 size 富文本標簽,
2.同一文本不能設(shè)置不同顏色的超鏈接文本
其它:代碼中注釋掉使用innerTextColor的地方,可以使用富文本設(shè)置超鏈接顏色, 但是下劃線是文本本身顏色

項目需要用到該功能, 搜索和參考了很多文章,要么不支持富文本,要不沒有下劃線,要么是錯誤的,修修改改后滿足我的需求,代碼如下

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

namespace MyTool.Tools
{
    /// <summary>
    /// 文本控件支持超鏈接、下劃線
    /// </summary>
    public class HyperlinkText : Text, IPointerClickHandler
    {
        public Action<string> onHyperlinkClick;

        /// 超鏈接信息類
        private class HyperlinkInfo
        {
            public int startIndex;
            public int endIndex;
            public string name;
            public readonly List<Rect> boxes = new List<Rect>();
            public List<int> linefeedIndexList = new List<int>();
        }

        /// 解析完最終的文本
        private string m_OutputText;

        /// 超鏈接信息列表
        private readonly List<HyperlinkInfo> m_HrefInfos = new List<HyperlinkInfo>();

        /// 文本構(gòu)造器
        protected StringBuilder s_TextBuilder = new StringBuilder();

        [Tooltip("超鏈接文本顏色")]
        [SerializeField] private Color32 innerTextColor = new Color32(36, 64, 180, 255);

        /// 超鏈接正則
        private static readonly Regex s_HrefRegex = new Regex(@"<href=([^>\n\s]+)>(.*?)(</href>)", RegexOptions.Singleline);

        // ugui富文本標簽
        // 格式1:<b></b>  <i></i>
        private static readonly string[] _uguiSymbols1 = { "b", "i" };
        // 格式2:<color=#ffffff></color> <color=red></color>
        private static readonly string[] _uguiSymbols2 = { "color", "size" };

        public string GetHyperlinkInfo { get { return text; } }

        public override void SetVerticesDirty()
        {
            base.SetVerticesDirty();

            text = GetHyperlinkInfo;
            m_OutputText = GetOutputText(text);
        }

        protected override void OnPopulateMesh(VertexHelper toFill)
        {
            var orignText = m_Text;
            m_Text = m_OutputText;
            base.OnPopulateMesh(toFill);
            m_Text = orignText;
            UIVertex vert = new UIVertex();

            // 處理超鏈接包圍框
            foreach (var hrefInfo in m_HrefInfos)
            {
                hrefInfo.boxes.Clear();
                hrefInfo.linefeedIndexList.Clear();
                if (hrefInfo.startIndex >= toFill.currentVertCount)
                    continue;

                // 將超鏈接里面的文本頂點索引坐標加入到包圍框
                toFill.PopulateUIVertex(ref vert, hrefInfo.startIndex);

                var pos = vert.position;
                var bounds = new Bounds(pos, Vector3.zero);
                hrefInfo.linefeedIndexList.Add(hrefInfo.startIndex);
                for (int i = hrefInfo.startIndex, m = hrefInfo.endIndex; i < m; i++)
                {
                    if (i >= toFill.currentVertCount)
                        break;

                    toFill.PopulateUIVertex(ref vert, i);
                    vert.color = innerTextColor;
                    toFill.SetUIVertex(vert, i);

                    pos = vert.position;

                    bool needEncapsulate = true;

                    if (i > 4 && (i - hrefInfo.startIndex) % 4 == 0)
                    {
                        UIVertex lastV = new UIVertex();
                        toFill.PopulateUIVertex(ref lastV, i - 4);
                        var lastPos = lastV.position;

                        if (pos.x < lastPos.x && pos.y < lastPos.y) // 換行重新添加包圍框
                        {
                            hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
                            hrefInfo.linefeedIndexList.Add(i);
                            bounds = new Bounds(pos, Vector3.zero);
                            needEncapsulate = false;
                        }
                    }
                    if (needEncapsulate)
                    {
                        bounds.Encapsulate(pos); // 擴展包圍框
                    }
                }
                hrefInfo.boxes.Add(new Rect(bounds.min, bounds.size));
            }

            //一個字一個字的劃 效率差 而且字與字之間容易有接縫
            DrawUnderLine(toFill);
        }

        private void DrawUnderLine(VertexHelper vh)
        {
            UIVertex vert = new UIVertex();
            List<Vector3> startPosList = new List<Vector3>();
            List<Vector3> endPosList = new List<Vector3>();
            foreach (var hrefInfo in m_HrefInfos)
            {
                if (hrefInfo.startIndex >= vh.currentVertCount) continue;

                float minY = float.MaxValue;
                for (int i = hrefInfo.startIndex, m = hrefInfo.endIndex; i < m; i += 4)
                {
                    if (i >= vh.currentVertCount)
                        break;

                    if (hrefInfo.linefeedIndexList.Contains(i))
                    {
                        for (int j = 0; j < startPosList.Count; j++)
                        {
                            MeshUnderLine(vh, new Vector2(startPosList[j].x, minY), new Vector2(endPosList[j].x, minY));
                        }
                        startPosList.Clear();
                        endPosList.Clear();
                    }

                    vh.PopulateUIVertex(ref vert, i + 3);
                    startPosList.Add(vert.position);
                    vh.PopulateUIVertex(ref vert, i + 2);
                    endPosList.Add(vert.position);

                    if (vert.position.y < minY)
                    {
                        minY = vert.position.y;
                    }
                }

                for (int j = 0; j < startPosList.Count; j++)
                {
                    MeshUnderLine(vh, new Vector2(startPosList[j].x, minY), new Vector2(endPosList[j].x, minY));
                }
                startPosList.Clear();
                endPosList.Clear();
            }
        }

        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;/*new UIVertex[4];*///"_"的的頂點數(shù)組

            Vector3[] pos = new Vector3[4];
            pos[0] = startPos + new Vector2(-1f, 0);
            pos[3] = startPos + new Vector2(-1f, 4f);
            pos[2] = endPos + new Vector2(1f, 4f);
            pos[1] = endPos + new Vector2(1f, 0);


            UIVertex[] tempVerts = new UIVertex[4];
            for (int i = 0; i < 4; i++)
            {
                tempVerts[i] = lineVer[i];
                tempVerts[i].color = innerTextColor;
                tempVerts[i].position = pos[i];
            }

            vh.AddUIVertexQuad(tempVerts);
        }

        /// <summary>
        /// 獲取超鏈接解析后的最后輸出文本
        /// </summary>
        /// <returns></returns>
        protected virtual string GetOutputText(string outputText)
        {
            s_TextBuilder.Length = 0;
            m_HrefInfos.Clear();
            var indexText = 0;
            int count = 0;
            foreach (Match match in s_HrefRegex.Matches(outputText))
            {
                string appendStr = outputText.Substring(indexText, match.Index - indexText);

                s_TextBuilder.Append(appendStr);

                //空格和回車沒有頂點渲染,所以要去掉
                count += appendStr.Length - appendStr.Replace(" ", "").Replace("\n", "").Length;
                //去掉富文本標簽的長度
                for (int i = 0; i < _uguiSymbols1.Length; i++)
                {
                    count += appendStr.Length - appendStr.Replace($"<{_uguiSymbols1[i]}>", "").Replace($"</{_uguiSymbols1[i]}>", "").Length;
                }
                for (int i = 0; i < _uguiSymbols2.Length; i++)
                {
                    string pattern = $"<{_uguiSymbols2[i]}=(.*?)>";
                    count += appendStr.Length - Regex.Replace(appendStr, pattern, "").Length;
                    count += appendStr.Length - appendStr.Replace($"</{_uguiSymbols2[i]}>", "").Length;
                }

                int startIndex = (s_TextBuilder.Length - count) * 4;
                var group = match.Groups[1];
                var hrefInfo = new HyperlinkInfo
                {
                    startIndex = startIndex, // 超鏈接里的文本起始頂點索引
                    endIndex = startIndex + (match.Groups[2].Length * 4),
                    name = group.Value
                };
                m_HrefInfos.Add(hrefInfo);

                s_TextBuilder.Append(match.Groups[2].Value);
                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 = Vector2.zero;
            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))
                    {
                        if (onHyperlinkClick != null)
                            onHyperlinkClick.Invoke(hrefInfo.name);

                        return;
                    }
                }
            }
        }



#if UNITY_EDITOR
		//需延遲調(diào)用該方法
        private void AddVisibleBound()
        {
            int index = 0;

            foreach (var hrefInfo in m_HrefInfos)
            {
                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 hrefInfo.boxes)
                {
                    GameObject gameObject = new GameObject();
                    gameObject.name = string.Format("GOBoundBox[{0}]", hrefInfo.name);
                    gameObject.transform.SetParent(this.gameObject.transform, false);

                    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;
                }
            }
        }
#endif
    }
}

編輯器擴展
unity下劃線,unity,windows
代碼

using UnityEditor;
using UnityEngine;

namespace MyTool
{
    [CanEditMultipleObjects]
    [CustomEditor(typeof(Tools.HyperlinkText), true)]
    public class HyperlinkTextEditor : UnityEditor.UI.TextEditor
    {
        SerializedProperty _innerTextColor;

        protected override void OnEnable()
        {
            base.OnEnable();
            _innerTextColor = serializedObject.FindProperty("innerTextColor");
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            serializedObject.Update();
            EditorGUILayout.PropertyField(_innerTextColor, new GUIContent("Inner Text Color"));
            serializedObject.ApplyModifiedProperties();
            if (GUI.changed)
            {
                EditorUtility.SetDirty(target);
            }
        }
    }
}

Demo代碼

using MyTool.Tools;
using System.Collections;
using UnityEngine;

public class Demo2 : MonoBehaviour
{
    public HyperlinkText text;
    // Start is called before the first frame update
    void Start()
    {
        //設(shè)置點擊回調(diào)
        text.onHyperlinkClick = OnClickText;

        StartCoroutine(AddVisibleBound());
    }

    IEnumerator AddVisibleBound()
    {
        yield return null;
        text.AddVisibleBound();
    }

    void OnClickText(string s)
    {
        if (s == "第一段第一句")
        {
            Debug.Log($"111---{s}");
        }
        else if (s == "第二段第一句")
        {
            Debug.Log($"222---{s}");
        }
        else
        {
            Debug.Log($"333---{s}");
        }
    }
}

demo測試文本

<color=#ffffff><b><size=36>背著手踱著。</size></b></color><color=ffffff><href=第一段第一句>路上只我一個人</href></color>,<size=45>這一片天地好像是我的;我也像超出了平常旳自己,到了另一世界里。我愛熱鬧,也愛冷靜;愛群居,也愛獨處。像今晚上,一個人在這蒼茫旳月下,什么都可以想,什么都可以不想,便覺是個自由的人。</size>白天里一定要做的事,一定要說的話,現(xiàn)在都可不理。<b><color=green>這是獨處的妙處,我且受用這無邊的荷香月色好了。</color></b>

<href=第二段第一句>曲曲折折的荷塘上面</href>,彌望旳是田田的葉子。葉子出水很高,像亭亭旳舞女旳裙。層層的葉子中間,零星地點綴著些白花,有裊娜(niǎo,nuó)地開著旳,有羞澀地打著朵兒旳;正如一粒粒的明珠,又如碧天里的星星,又如剛出浴的美人。微風(fēng)過處,送來縷縷清香,仿佛遠處高樓上渺茫的歌聲似的。這時候葉子與花也有一絲的顫動,像閃電般,霎時傳過荷塘的那邊去了。葉子本是肩并肩密密地挨著,這便宛然有了一道凝碧的波痕。葉子底下是脈脈()的流水,遮住了,不能見一些顏色;而葉子卻更見風(fēng)致了。

<size=60>月光如流水一般,靜靜地瀉在這一片葉子和花上。薄薄的青霧浮起在荷塘里。葉子和花仿佛在牛乳中洗過一樣;又像籠著輕紗的夢。雖然是滿月,天上卻有一層淡淡的云,所以不能朗照;但我以為</size>這恰是到了好處——酣眠固不可少,小睡也別有風(fēng)味的。月光是隔了樹照過來的,高處叢生的灌木,落下參差的斑駁的黑影,峭楞楞如鬼一般;彎彎的楊柳的稀疏的倩影,卻又像是畫在荷葉上。塘中的月色并不均勻;但光與影有著和諧的旋律,<href=第三段>如梵婀(ē)(英語violin小提琴的譯音)上奏著的名曲</href>。

<color=red><i>荷塘的四面,遠遠近近,高高低低都是樹,而楊柳最多。</i></color><href=第四段>這些樹將一片荷塘重重圍住</href>;只在小路一旁,漏著幾段空隙,像是特為月光留下的。樹色一例是陰陰的,乍看像一團煙霧;但楊柳的豐姿,便在煙霧里也辨得出。樹梢上隱隱約約的是一帶遠山,只有些大意罷了。樹縫里也漏著一兩點路燈光,沒精打采的,是渴睡人的眼。這時候最熱鬧的,要數(shù)樹上的蟬聲與水里的蛙聲;但熱鬧是它們的,我什么也沒有。

ui
unity下劃線,unity,windows
效果
unity下劃線,unity,windows文章來源地址http://www.zghlxwxcb.cn/news/detail-771169.html

到了這里,關(guān)于unity ugui text 超鏈接和下劃線,支持部分富文本格式的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • HTML中設(shè)定下劃線樣式并且指定下劃線長度

    HTML中設(shè)定下劃線樣式并且指定下劃線長度

    今天筆者在寫網(wǎng)頁導(dǎo)航欄時,想要給鏈接加一個懸停下劃線,寫出來如下 HTMl: CSS:(關(guān)于其他格式的設(shè)定略,只看下劃線這一段代碼) 這樣確實是設(shè)定下劃線了,但是效果如下,看上去很難看 既然這樣,那么該如何改變一下呢? 其實可以使用border-bottom來實現(xiàn),代碼如下

    2024年02月10日
    瀏覽(19)
  • css 下劃線

    在 CSS 中,可以使用 \\\"text-decoration\\\" 屬性來設(shè)置文本的下劃線。例如: 這會使所有的段落文本都帶有下劃線。你也可以使用 \\\"text-decoration-style\\\" 屬性來設(shè)置下劃線的樣式,例如實線、虛線或點線等。 你還可以使用 \\\"border-bottom\\\" 屬性來設(shè)置下劃線,例如: 這會在段落文本下方添加

    2024年02月12日
    瀏覽(20)
  • css下劃線跟隨導(dǎo)航

    css下劃線跟隨導(dǎo)航

    2024年01月23日
    瀏覽(22)
  • a標簽設(shè)置下劃線動畫

    a標簽設(shè)置下劃線動畫

    ?

    2024年02月07日
    瀏覽(22)
  • React Native文本添加下劃線

    React Native文本添加下劃線

    2024年02月13日
    瀏覽(25)
  • Java實現(xiàn)駝峰、下劃線互轉(zhuǎn)

    Java實現(xiàn)駝峰、下劃線互轉(zhuǎn)

    Java實現(xiàn)駝峰、下劃線互轉(zhuǎn) 1.使用 Guava 實現(xiàn) 先引入相關(guān)依賴 1.2 下劃線轉(zhuǎn)駝峰 2.自定義代碼轉(zhuǎn) 2.1駝峰轉(zhuǎn)下劃線 2.2下劃線轉(zhuǎn)駝峰

    2024年02月12日
    瀏覽(22)
  • 電腦下劃線在鍵盤上怎么打出來

    電腦下劃線在鍵盤上怎么打出來

    電腦下劃線在鍵盤上怎么打出來, 可能很多人在打字的過程中都不知道如何在鍵盤上輸入下劃線的符號,本期內(nèi)容就和大家詳細介紹一些電腦打出下劃線的方法吧。 1、電腦大鍵盤。大鍵盤區(qū)域找到右上角有個 - 線就是中橫線,使用shift+- 即可輸入下劃線。 2、注意下劃線輸入

    2024年02月07日
    瀏覽(18)
  • echarts 餅圖 環(huán)形圖 lable添加下劃線
  • python里面單雙下劃線的區(qū)別

    python里面單雙下劃線的區(qū)別

    區(qū)別: xx:公有變量,所有對象都可以訪問; xxx :雙下劃線代表著是系統(tǒng)定義的名字。 __xxx:雙前置下劃線,避免與子類中的屬性命名沖突,無法在外部直接訪問。代表著類中的私有變量名。 _xxx:單前置下劃線,私有化屬性和方法,類對象和子類可以訪問。不能用“from modu

    2023年04月24日
    瀏覽(20)
  • 【CSS】鼠標(移入/移出)平滑(顯示/隱藏)下劃線

    【CSS】鼠標(移入/移出)平滑(顯示/隱藏)下劃線

    鼠標移入內(nèi)容時,下劃線從 左 開始繪制到 右 側(cè)結(jié)束 鼠標移出內(nèi)容時,下劃線從 左 開始擦除到 右 側(cè)結(jié)束 我們給內(nèi)容添加一個黑色背景 background: #000; 示例 效果 將黑色背景 background: #000; 替換成彩色漸變背景 background: linear-gradient(to right,#ec695c,#61c454); 示例 效果 寬度設(shè)置100個

    2024年02月09日
    瀏覽(26)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包