UGUI Text組件實際文本寬高的獲取


Text.preferreHeight這個值是當前Text組件中所有文字的實際總高度,由此,可以衍生出以下兩種非常實用的操作


1、獲取一行文本的方法:

void Start()
    {
        Text text = GetComponent<Text>();
        text.text = "";
        float lineHeight = text.preferredHeight;
<span style="white-space:pre">	</span>// 自己的操作
    }


2、獲取文本的行數:

int GetLineCount()
    {
        Text tex = GetComponent<Text>();
        string strText = tex.text;
        tex.text = "";
        float linrHeight = tex.preferredHeight;
        tex.text = strText;

        return (int)(tex.preferredHeight / height);
    }

不過在實際應用中可以靈活實用,比如:


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


public class TextModeTest : MonoBehaviour
{
    Text text;
    int i = 1000;
    float height = 0f;
    
    void Start()
    {
        text = GetComponent<Text>();
        text.text = "";
        height = text.preferredHeight;
    }
    
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            text.text += i.ToString();
            ++i;
            Debug.Log("行數 :" + GetLineCount() + "    高度:" + text.preferredHeight);
        }
    }

    int GetLineCount()
    {
        return (int)(text.preferredHeight / height);
    }
}


Text.preferreHeight這個值是當前Text組件中所有文字的實際總高度,由此,可以衍生出以下兩種非常實用的操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章