自己实现Text控件 - 把文本显示出来
最终效果
就简简单单一个利用Font把文本渲染出来
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)