UGUI 文本下划线实现

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
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值