UGUI 文本对齐格式化

using UnityEngine;
using UnityEngine.UI;
using Text = UnityEngine.UI.Text;
[RequireComponent(typeof(Text))]
public class TextFormatting : BaseMeshEffect
{
    [SerializeField]
    [Header("多行对齐方式:默认UpperLeft")]
    private TextAnchor multiline = TextAnchor.UpperLeft;
    [SerializeField]
    [Header("单行对齐方式:默认MiddleCenter")]
    private TextAnchor singleLine = TextAnchor.MiddleCenter;
    
    private Text textComponent;
    private string content = "";
    private float textCompentWidth = 0;

    protected override void OnEnable()
    {
        base.OnEnable();
        if (textComponent == null)
        {
            textComponent = GetComponent();
        }

        textCompentWidth = textComponent.rectTransform.rect.width;
        textComponent.RegisterDirtyVerticesCallback(ReplaceSpace);
    }

    public override void ModifyMesh(VertexHelper vh)
    {
        if (!IsActive())
            return;
    }

    void ReplaceSpace()
    {
        // 获取文本行数 废弃
        // int lineCount = textCompent.cachedTextGenerator.lineCount;
        content = textComponent.text;
        float width = CalculateLengthOfText(content, textComponent);
        if (content.Contains("\u3000"))
        {
            content = content.Replace("\u3000", "");
        }

        if (width > textCompentWidth)
        {
            content = $"\u3000\u3000{content}";
            //首行缩进
            textComponent.alignment = multiline;
        }
        else
        {
            //文本居中
            textComponent.alignment = singleLine;
        }

        textComponent.text = content;
    }

    // 计算文本内容长度
    int CalculateLengthOfText(string message, Text tex)
    {
        int totalLength = 0;
        Font myFont = tex.font;
        myFont.RequestCharactersInTexture(message, tex.fontSize, tex.fontStyle);
        CharacterInfo characterInfo = new CharacterInfo();
        char[] arr = message.ToCharArray();
        foreach (char c in arr)
        {
            myFont.GetCharacterInfo(c, out characterInfo, tex.fontSize);
            totalLength += characterInfo.advance;
        }

        return totalLength;
    }
}

你可能感兴趣的:(UGUI,Unity,UGUI,Text)