【Unity】Text添加文字下劃線

UGUI的Text本身是沒有下劃線或者文字中間的劃去橫線的。使用此組件,選擇Text和劃線類型:spa

1.設置autoLink=true,運行後自動克隆相同的文本組件,計算文字長度,給克隆的Text填充"_"或者"-";code

2.調用CreateLink方法,爲指定Text文本添加下劃線orm

3.此組件暫時用於固定文本,或僅用於一次展現的文本,同一個文本動態修改的時候應當先刪除子物體中的下劃線文本blog


 

如:給Text添加UnderLineText組件,設置LinkText爲本身,UnderLineType爲Bottom,AutoLink=true;string

 運行後會爲原來的Text添加一個子物體Text組件,填充「___」it

 

 

 

 

 另:文本中有回車時候會沒法轉換。io


 

完整代碼:form

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public enum UnderLineType
{
    //畫線位置
    Bottom = 0,
    Center
}

//文本編輯擴展
public class UnderLineText : MonoBehaviour
{
    public Text linkText;
    public UnderLineType underLineType;
    public bool autoLink = true;
    private string underLineText = "_";

    private void Awake()
    {
        if (underLineType == UnderLineType.Bottom)
        {
            underLineText = "_";
        }
        else
        {
            underLineText = "-";
        }
    }

    private void Start()
    {
        if (autoLink)
            CreateLink(linkText, null);
    }

    public void CreateLink(Text text, UnityEngine.Events.UnityAction onClickBtn = null)
    {
        if (text == null)
            return;

        //克隆Text,得到相同的屬性
        Text underline = Instantiate(text) as Text;
        underline.name = "Underline";
        underline.transform.SetParent(text.transform);
        underline.transform.localScale = Vector3.one;
        RectTransform rt = underline.rectTransform;
        //設置下劃線座標和位置
        rt.anchoredPosition3D = Vector3.zero;
        rt.offsetMax = Vector2.zero;
        rt.offsetMin = Vector2.zero;
        rt.anchorMax = Vector2.one;
        rt.anchorMin = Vector2.zero;
        underline.text = underLineText;
        float perlineWidth = underline.preferredWidth;      //單個下劃線寬度
        float width = text.preferredWidth;
        int lineCount = (int)Mathf.Round(width / perlineWidth);
        for (int i = 1; i < lineCount; i++)
        {
            underline.text += underLineText;
        }
        if (onClickBtn != null)
        {
            var btn = text.gameObject.AddComponent<Button>();
            btn.onClick.AddListener(onClickBtn);
        }
        var underLine = underline.GetComponent<UnderLineText>();
        if (underLine)
        {
            underLine.autoLink = false;
        }
    }
}
相關文章
相關標籤/搜索