44 lines
1.1 KiB
C#
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());
|
|
}
|
|
|
|
}
|