我正在使用stb_truetype在OpenGL上下文中呈现TrueType字体。

有什么简单的方法可以在呈现字体之前预先确定字符串的高度和宽度?

最佳答案

LWJGL STB True Type演示包含了此实现(自2017年8月开始),包括字距调整:

lwjgl3 / Truetype.java

private float getStringWidth(STBTTFontinfo info, String text, int from, int to, int fontHeight) {
    int width = 0;

    try (MemoryStack stack = stackPush()) {
        IntBuffer pCodePoint       = stack.mallocInt(1);
        IntBuffer pAdvancedWidth   = stack.mallocInt(1);
        IntBuffer pLeftSideBearing = stack.mallocInt(1);

        int i = from;
        while (i < to) {
            i += getCP(text, to, i, pCodePoint);
            int cp = pCodePoint.get(0);

            stbtt_GetCodepointHMetrics(info, cp, pAdvancedWidth, pLeftSideBearing);
            width += pAdvancedWidth.get(0);

            if (isKerningEnabled() && i < to) {
                getCP(text, to, i, pCodePoint);
                width += stbtt_GetCodepointKernAdvance(info, cp, pCodePoint.get(0));
            }
        }
    }

    return width * stbtt_ScaleForPixelHeight(info, fontHeight);
}

private static int getCP(String text, int to, int i, IntBuffer cpOut) {
    char c1 = text.charAt(i);
    if (Character.isHighSurrogate(c1) && i + 1 < to) {
        char c2 = text.charAt(i + 1);
        if (Character.isLowSurrogate(c2)) {
            cpOut.put(0, Character.toCodePoint(c1, c2));
            return 2;
        }
    }
    cpOut.put(0, c1);
    return 1;
}

08-17 20:42