YanCheng_Metrology/Assets/Scripts/Tsq/AutoResizeImage.cs

36 lines
892 B
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using TMPro;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(RectTransform))]
public class AutoResizeImage : MonoBehaviour
{
public TMP_Text contentText;
private RectTransform backgroundImageRect;
void Start()
{
backgroundImageRect = GetComponent<RectTransform>();
AdjustImageWidth();
}
void Update()
{
AdjustImageWidth();
}
void AdjustImageWidth()
{
// 获取 Text 组件的首选宽度
float preferredWidth = contentText.preferredWidth;
// 设置 Image 的宽度为 Text 的首选宽度,加上一些 padding假设为 20
backgroundImageRect.sizeDelta = new Vector2(preferredWidth + (contentText.text == "" ? 0 : 30), backgroundImageRect.sizeDelta.y);
contentText.GetComponent<RectTransform>().sizeDelta = new Vector2(preferredWidth + (contentText.text == "" ? 0 : 30), 52);
}
}