• QQ
  • nahooten@sina.com
  • 常州市九洲新世界花苑15-2

游戏开发

UGUI Text组件实际文本宽高的获取

原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1116/190.html

UGUI Text组件实际文本宽高的获取


Text.preferreHeight这个值是当前Text组件中所有文字的实际总高度,由此,可以衍生出以下两种非常实用的操作

 

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

void Start()

    {

        Text text = GetComponent<Text>();

        text.text = "";

        float lineHeight = text.preferredHeight;

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);

    }

}



上篇:上一篇:asp.net使用mysql数据库
下篇:下一篇:U3D非xml的字符串变规范的xml