如何在Unity3D中计算组按钮的自动大小

我使用TextMeshPro拥有按钮的水平布局组。如何计算自动调整字体大小并在所有按钮上设置最小值?需要相对的UI。

我现在有:

如何在Unity3D中计算组按钮的自动大小

以及我想要的方式:

如何在Unity3D中计算组按钮的自动大小

我尝试了以下代码:

public class FontSizeController: MonoBehaviour
{
    private void Start()
    {
        SetMinFontForAnswers(transform,FindMinFontSizeAnswerOptions(transform));
    }

    private void SetMinFontForAnswers(Transform answerPanel,float minFontSize)
    {
        for (var answerIndex = 0; answerIndex < answerPanel.childCount; answerIndex++)
        {
            var meshProUgui = answerPanel.getchild(answerIndex).getchild(1).getcomponent<TextMeshProUGUI>();
            meshProUgui.fontSize = minFontSize;
        }
    }

    private float FindMinFontSizeAnswerOptions(Transform answerOptions)
    {
        var minFontSize = -1f;

        for (var answerIndex = 0; answerIndex < answerOptions.childCount; answerIndex++)
        {
            var component = answerOptions.getchild(answerIndex).getchild(1).getcomponent<TextMeshProUGUI>();
            component.enableAutoSizing = true;
            component.ForceMeshUpdate();
            if (IsAnswerOptionactive(answerOptions,answerIndex) && IsMinFontSizeOrNotInitialized(component,minFontSize))
            {
                minFontSize = component.fontSize;
            }

            component.enableAutoSizing = false;
        }

        return minFontSize;
    }

    private bool IsAnswerOptionactive(Transform answerOptions,int answerIndex)
    {
        return answerOptions.getchild(answerIndex).gameObject.activeSelf;
    }
    private bool IsMinFontSizeOrNotInitialized(TMP_Text textComponent,float minFontSize)
    {
        return textComponent.fontSize < minFontSize || minFontSize == -1f;
    }

}

但是它不适用于“开始”,并且仅适用于“更新”方法。但是,当我在Update方法中使用它时,我可以看到文本字体大小发生了变化。很快,但是我想在面板渲染之前执行此操作。

默认情况下,问题面板不处于活动状态

如何在Unity3D中计算组按钮的自动大小

AnswerOptionsPanel:

如何在Unity3D中计算组按钮的自动大小

answerOptionsPanel中的TextMeshPro文本:

如何在Unity3D中计算组按钮的自动大小

bluemoon88888 回答:如何在Unity3D中计算组按钮的自动大小

使用此方法,您可以获取文本资产的当前大小;

Text.cachedTextGenerator.fontSizeUsedForBestFit

您可以比较文本的即时大小,然后进行更改。 例如;

UnityEngine.UI.Text[] myTexts;

void OptimiseTextSizes()
{

    int minSize = 999;
    foreach (UnityEngine.UI.Text t in myTexts)
    {
        if (t.cachedTextGenerator.fontSizeUsedForBestFit < minSize)
        {
            minSize = t.cachedTextGenerator.fontSizeUsedForBestFit;
        }
    }

    foreach (UnityEngine.UI.Text t in myTexts)
    {
        t.resizeTextMaxSize = minSize;
    }

}
本文链接:https://www.f2er.com/3150074.html

大家都在问