Font - ttf字体

Dynamic字符

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

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

 

2) 使用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}");
}

 

3) 使用Font.RequestCharactersInTexture来向字体贴图中渲染新的字符

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

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

 

设置为Custom Set字符

1) 字体贴图上的字符就固定了

调用m_Font.RequestCharactersInTexture("defg", 50); defg不会再被渲染到字体贴图上

m_Font.GetCharacterInfo('d', out var charInfo, 50)也拿不到字符信息

 

2) Font Size很小

Text想把fontSize设大,结果会很糊

原因:字符贴图上的字符就是按10这个大小渲染好的,当Text设置为100时,也不会再渲染100大小的字符到贴图上,而是直接用10的放大

 

监听字体贴图重新生成

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

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

void OnFontTextureRebuilt(Font f)
{
    //todo
}

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

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

 

打印字体信息

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}");
}

 

posted @ 2023-06-29 01:36  yanghui01  阅读(185)  评论(0编辑  收藏  举报