UGUI 文本下划线实现

来源:互联网 发布:js 遇见未来下载 编辑:程序博客网 时间:2024/06/07 03:38
UGUI富文本好像没有支持下划线(到5.2.2),自己封装了一个简单的,可当链接点击跳转。
[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using UnityEngine.UI;  
  4.   
  5. public class LinkButton : MonoBehaviour {  
  6.   
  7.     private Text linkText;  
  8.   
  9.     void Awake()  
  10.     {  
  11.         linkText = transform.Find("Text").GetComponent<Text>();  
  12.   
  13.     }  
  14.     void Start ()   
  15.     {  
  16.         CreateLink(linkText, onButtonClick);  
  17.     }  
  18.   
  19.     public void CreateLink(Text text,UnityEngine.Events.UnityAction onClickBtn)  
  20.     {  
  21.         if (text == null)  
  22.             return;  
  23.   
  24.         //克隆Text,获得相同的属性  
  25.         Text underline = Instantiate(text) as Text;  
  26.         underline.name = "Underline";  
  27.   
  28.         underline.transform.SetParent(text.transform);  
  29.         RectTransform rt = underline.rectTransform;  
  30.   
  31.         //设置下划线坐标和位置  
  32.         rt.anchoredPosition3D = Vector3.zero;  
  33.         rt.offsetMax = Vector2.zero;  
  34.         rt.offsetMin = Vector2.zero;  
  35.         rt.anchorMax = Vector2.one;  
  36.         rt.anchorMin = Vector2.zero;  
  37.   
  38.         underline.text = "_";  
  39.         float perlineWidth = underline.preferredWidth;      //单个下划线宽度  
  40.         Debug.Log(perlineWidth);  
  41.   
  42.         float width = text.preferredWidth;  
  43.         Debug.Log(width);  
  44.         int lineCount = (int)Mathf.Round(width / perlineWidth);  
  45.         Debug.Log(lineCount);  
  46.         for(int i = 1;i < lineCount;i++)  
  47.         {  
  48.             underline.text += "_";  
  49.         }  
  50.   
  51.         var btn = text.gameObject.AddComponent<Button>();  
  52.         btn.onClick.AddListener(onClickBtn);         
  53.     }  
  54.   
  55.     //点击响应  
  56.     void onButtonClick()  
  57.     {  
  58.         Debug.Log("onClick");  
  59.     }  
  60. }  
原理就是在原Text上加了一个内容是下划线的Text。
效果图:
0 0
原创粉丝点击