UGUI背景图片高度如何自适应

文字区内容少时如下图:


 文字区内容多时,背景图片自动调整如下图:


可以看见蓝色背景图的高度随着文字内容的多少 ,高度方向上自动调整,具体做法如下:





 



边框图片需要图片剪切一下,防止出现拉升变形




 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值