链接下划线的2种实现方式

发表于2017-06-06
评论1 4.1k浏览

       使用UGUI制作界面时,会遇到链接的使用,它一般都有下划线,下划线实现的方式大概有2种方式:第1种方式是在链接文本下方“拼接”下划线文本“_”实现;第2种方式是“拉伸”Image图片实现。实现脚本如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
/*
 * Author:LuShang
 * 链接下划线的制作
 */
public class UnderLine : MonoBehaviour {
    ///
    /// URL文本
    ///
    public GameObject URL;
    ///
    /// URL下划线文本
    ///
    public GameObject URL_UderLine;
    ///
    /// URL下划线Image
    ///
    public GameObject Line_Image;
    ///
    /// 实现下划线的方式类型
    ///
    public int Type = 0;
 
    // Use this for initialization
    void Start () {
 
        SetURLUnderLine(Type);
 
    }
     
    // Update is called once per frame
    void Update () {
         
    }
 
    ///
    /// 设定隐私协议文本的下划线
    /// type值为0表示使用“拼接Text:_”方式实现,有缺点
    /// type值为1表示使用“拉伸Image”方式实现,比较完美
    ///
    private void SetURLUnderLine(int type)
    {
        Debug.Log("设定隐私协议文本的下划线,方式:"+type);
 
         
 
        switch (type)
        {
            case 0:
                //计算URL文本的宽度
                URL.GetComponent().text = "www.baidu.com";
                float width = URL.GetComponent().preferredWidth;
 
                //计算单个下划线宽度 
                Text underLineText = URL_UderLine.GetComponent();
                underLineText.text = "_";
                float perlineWidth = underLineText.preferredWidth;
 
                int lineCount = (int)Mathf.Round(width / perlineWidth);
                for (int i = 1; i < lineCount; i++)
                {
                    underLineText.text += "_";
                }
                break;
            case 1:
                //计算URL文本的宽度
                URL.GetComponent().text = "www.xmutalbaa.com";
                float width2 = URL.GetComponent().preferredWidth;
 
                Vector2 curSizeDelta = Line_Image.GetComponent().sizeDelta;
                Line_Image.GetComponent().pivot = new Vector2(0, 0.5f);
                Line_Image.GetComponent().sizeDelta = new Vector2(width2, curSizeDelta.y);
                break;
        }
        
        
 
        
    }
}
        
      在场景中,创建分别实现这2种方式链接对象,并在父级挂上面的脚本且赋上值 ,如下截图所示:

     
      运行结果如下图所示:
      对比发现,第1种实现方式有缺点,不能够100%保证链接文本的长度与其下划线的长度一致,目前没想出怎么解决这个缺点;如果读者要在项目中用的话,建议使用第2种方式。欢迎读者@交流,谢谢!

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

0个评论