Font - ttf字体

发布时间 2023-06-29 01:43:38作者: yanghui01

打印字体信息

public static void PrintFontInfo(Font font)
{
    Debug.Log($"fontSize:{font.fontSize}, lineHeight:{font.lineHeight}, ascent:{font.ascent}");

    var so = new SerializedObject(font);
    PrintSpFloatValue(so, "m_FontSize");
    PrintSpFloatValue(so, "m_LineSpacing");
    PrintSpFloatValue(so, "m_Ascent");
    PrintSpFloatValue(so, "m_Descent");
}

private static void PrintSpFloatValue(SerializedObject so, string propName)
{
    var sp = so.FindProperty(propName);
    if (null != sp)
        Debug.Log($"{propName}: {sp.floatValue}");
}

 

Font的字体贴图

ttf字体默认是Dynamic的,就是用到什么字符,运行时渲染对应的字符到字体贴图上

比如:Text组件上的New Text,在运行起来后字体贴图就渲染了NewText上去

 

可以Font.GetCharacterInfo来获取字符信息

//不传fontSize参数, 大概率会fail, 因为不传默认会使用Font.fontSize, 和Text.fontSize不一样就fail了
if (m_Text.font.GetCharacterInfo('N', out var ch, m_Text.fontSize))
{
    Debug.Log($"get charInfo: index:{ch.index}, style:{ch.style}, fontSize:{ch.size}, width:{ch.glyphWidth}, width:{ch.glyphHeight}, adv:{ch.advance}");
}
else
{
    Debug.Log($"get charInfo fail: {m_Text.font.fontSize}");
}

 

执行下面的代码后,字体贴图增加了测试文本,而且他的大小是100的,比NewText明显大(35大小)

m_Text.font.RequestCharactersInTexture("测试文本", 100);

 

监听字体贴图重新生成

void OnEnable()
{
    Font.textureRebuilt += OnFontTextureRebuilt;
}

void OnDisable()
{
    Font.textureRebuilt -= OnFontTextureRebuilt;
}

void OnFontTextureRebuilt(Font f)
{
    //todo
}

什么情况下会重新生成呢?

比如贴图大小不够了,从256x256变成512x512这种