unity文本大小自适应文本框第一种方法
using System.Collections;
using System.Collections.Generic;
using UnityEditor.VersionControl;
using UnityEngine;
using UnityEngine.UI;
public class Test : MonoBehaviour
{
public enum StartAxisType
{
Horizontal,
Vertical
}
public bool mAdaptiveSize = false;
public StartAxisType mStartAxis = StartAxisType.Horizontal;
public int mBeginFontSize;
public Vector2 mRectSize;
public Text mText;
void Awake()
{
mRectSize = transform.GetComponent<RectTransform>().sizeDelta;
mText = transform.GetComponent<Text>();
mBeginFontSize = mText.fontSize;
}
void Start()
{
if (!mAdaptiveSize)
return;
switch (mStartAxis)
{
case StartAxisType.Horizontal:
while (mText.preferredWidth > mRectSize.x)
{
mText.fontSize -= 1;
}
break;
case StartAxisType.Vertical:
while (mText.preferredHeight > mRectSize.y)
{
mText.fontSize -= 1;
}
break;
}
}
}
第二种,直接设置text上的BestFit属性为true即可