文字区内容少时如下图:
文字区内容多时,背景图片自动调整如下图:
可以看见蓝色背景图的高度随着文字内容的多少 ,高度方向上自动调整,具体做法如下:
边框图片需要图片剪切一下,防止出现拉升变形
SimpleHight_Self_Adaption脚本内容如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using TMPro;
/// <summary>
/// text上的consizefetter组件取消掉
/// interval 属性 更改上下的间隙。
/// </summary>
public class SimpleHight_Self_Adaption : MonoBehaviour {
public TextMeshProUGUI text1;
public Text text2;
public float interval = 150;
private void Start()
{
ChangeText("999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
}
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
ChangeText("99999999999999999999999999999ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff999999977777777777777777777777777777777777777777777777777777777777777777777777777777777777777779999999999999999999999998888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888888899999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999");
}
}
private void OnEnable()
{
text1 = GetComponentInChildren<TextMeshProUGUI>();
text2 = GetComponentInChildren<Text>();
(transform as RectTransform).pivot = new Vector2(0.5f,0);
}
public void ChangeText(string text) {
if (text1)
{
text1.text = text;
SetTitleHint(text1.preferredHeight, text1.rectTransform);
}
if (text2)
{
text2.text = text;
SetTitleHint(text2.preferredHeight, text2.rectTransform);
}
}
void SetTitleHint(float prefabHight, RectTransform text)
{
text.sizeDelta = new Vector2(text.sizeDelta.x, prefabHight);
RectTransform rect = transform as RectTransform;
rect.sizeDelta = new Vector2(rect.sizeDelta.x, Mathf.Clamp(prefabHight + interval,295,1000) );
Canvas.ForceUpdateCanvases();
}
}
FR:海涛高软(Hunk Xu)