c1_unity/Assets/Scripts/Component/Helper/FixRectWidthByString.cs
2023-04-03 11:04:31 +08:00

44 lines
1.1 KiB
C#

using System;
using TMPro;
using UnityEngine;
[ExecuteInEditMode]
public class FixRectWidthByString : MonoBehaviour
{
public int minWidth = 40;
private TextMeshProUGUI textComp;
private void Awake()
{
textComp = GetComponentInChildren<TextMeshProUGUI>();
}
private void OnEnable()
{
SetRectSize();
}
private float GetTextWidth()
{
int width = 0;
if (textComp != null)
{
var txt = textComp.text;
var font = textComp.font.sourceFontFile;
CharacterInfo characterInfo;
font.RequestCharactersInTexture(txt, font.fontSize);
for (int i = 0; i < txt.Length; i++)
{
font.GetCharacterInfo(txt[i], out characterInfo, font.fontSize);
width += characterInfo.advance;
}
}
return width + minWidth;
}
[ContextMenu("激活")]
private void SetRectSize()
{
GetComponent<RectTransform>().SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal,GetTextWidth());
}
}