Text Bg ContentSizeFitter的另类控制
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(ContentSizeFitter))] public class textBgControl :UIBehaviour { public RectTransform parentRectTrans; private RectTransform rectTransform; protected override void Start() { rectTransform = GetComponent<RectTransform>(); } protected override void OnRectTransformDimensionsChange() { float height = GetWidthOrHeight(RectTransform.Axis.Vertical); parentRectTrans.sizeDelta = new Vector2(parentRectTrans.sizeDelta.x,height); } public float GetWidthOrHeight(RectTransform.Axis axis) { if (axis == RectTransform.Axis.Horizontal) return rectTransform.rect.width; return rectTransform.rect.height; } }
using UnityEngine; using UnityEngine.UI; public class Test : MonoBehaviour { public Text Text; void Start() { RectTransform rect = Text.GetComponent<RectTransform>(); // 获取Text的Size Vector2 v2 = rect.rect.size; Text.text = "这是一堆文字,具体多少我也不知道,反正就是一堆文字"; // width保持不变 rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, v2.x); // 动态设置height rect.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Text.preferredHeight); } }
https://blog.csdn.net/weixin_43149049/article/details/104005050
https://blog.csdn.net/qq_14914623