可横竖控制的Text bg Control
using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(ContentSizeFitter))] public class textBgControl : UIBehaviour { public int maxWidth = 630; public int defaultHeight = 60; private RectTransform bgRectTrans; private RectTransform rectTrans; private ContentSizeFitter sizeFitter; private Text text; private Vector2 sizedelta; void Start () { bgRectTrans = transform.parent.GetComponent<RectTransform>(); rectTrans = GetComponent<RectTransform>(); text = GetComponent<Text>(); } protected override void OnRectTransformDimensionsChange() { bgRectTrans = transform.parent.GetComponent<RectTransform>(); rectTrans = GetComponent<RectTransform>(); text = GetComponent<Text>(); sizeFitter = GetComponent<ContentSizeFitter>(); if (rectTrans.sizeDelta.x > maxWidth) { text.horizontalOverflow = HorizontalWrapMode.Wrap; float height = GetWidthOrHeight(RectTransform.Axis.Vertical); sizedelta.Set(maxWidth, height); bgRectTrans.sizeDelta = sizedelta; } else { float width = GetWidthOrHeight(RectTransform.Axis.Horizontal); sizedelta.Set(width,defaultHeight); bgRectTrans.sizeDelta = sizedelta; } } public float GetWidthOrHeight(RectTransform.Axis axis) { if (axis == RectTransform.Axis.Horizontal) return rectTrans.rect.width; return rectTrans.rect.height; } }
https://blog.csdn.net/qq_14914623