自定义UGUI控件 - 实现一个Text控件Demo

发布时间 2023-06-29 01:53:47作者: yanghui01

最终效果

 

就简简单单一个利用Font把文本渲染出来的Demo,文字排版啥的都没没有

using UnityEngine;
using UnityEngine.UI;

public class MyText : Graphic
{
    public Font m_Font;
    public string m_Text = "Hellow World";
    public int m_FontSize = 40;

    public Color m_FontColor = Color.white;

    protected MyText()
    {
        useLegacyMeshGeneration = false;
    }

    /*
    protected override void OnEnable()
    {
    base.OnEnable();
    Font.textureRebuilt += OnFontTextureRebuilt;
    }

    void OnFontTextureRebuilt(Font font)
    {
    if (font != m_Font) //其他字体的忽略
    return;

    SetVerticesDirty();
    }

    protected override void OnDisable()
    {
    Font.textureRebuilt -= OnFontTextureRebuilt;
    base.OnDisable();
    }
    */

    //这个必须要提供, OnPopulateMesh中的顶点的uv对应的是这个贴图上的
    public override Texture mainTexture
    {
        get
        {
            if (m_Font != null && m_Font.material != null && m_Font.material.mainTexture != null)
                return m_Font.material.mainTexture;

            return base.mainTexture; //默认的白色图片
        }
    }

    readonly UIVertex[] m_TempVerts = new UIVertex[4];

    protected override void OnPopulateMesh(VertexHelper vh)
    {
        vh.Clear();
        if (null == m_Font)
            return;

        m_Font.RequestCharactersInTexture(m_Text, m_FontSize);

        Vector3 pos = Vector3.zero;
        m_Font.RequestCharactersInTexture(m_Text, m_FontSize);
        for (int i = 0; i < m_Text.Length; i++)
        {
            // Get character rendering information from the font
            m_Font.GetCharacterInfo(m_Text[i], out var ch, m_FontSize);

            m_TempVerts[0].position = pos + new Vector3(ch.minX, ch.maxY, 0); //左上角
            m_TempVerts[0].color = m_FontColor;
            m_TempVerts[0].uv0 = ch.uvTopLeft;

            m_TempVerts[1].position = pos + new Vector3(ch.maxX, ch.maxY, 0);
            m_TempVerts[1].color = m_FontColor;
            m_TempVerts[1].uv0 = ch.uvTopRight;

            m_TempVerts[2].position = pos + new Vector3(ch.maxX, ch.minY, 0);
            m_TempVerts[2].color = m_FontColor;
            m_TempVerts[2].uv0 = ch.uvBottomRight;

            m_TempVerts[3].position = pos + new Vector3(ch.minX, ch.minY, 0);
            m_TempVerts[3].color = m_FontColor;
            m_TempVerts[3].uv0 = ch.uvBottomLeft;

            //0,1,2; 0,2,3
            vh.AddUIVertexQuad(m_TempVerts);
            
            if (i > 0 && 0 == i % 3) //3个字符换行
            {
                pos.y -= (m_FontSize / m_Font.fontSize) * m_Font.lineHeight;
                pos.x = 0;
            }

            pos.x += ch.advance; // Advance character position
        }
    }

}

 

参考

写个自研的图文混排(四)自己写个文字类 - 知乎 (zhihu.com)