Hello, I'm trying to calculate the width of a font string when using stb_truetype. I render my font like so:
try (MemoryStack stack = stackPush()) {
FloatBuffer x = stack.floats(0.0f);
FloatBuffer y = stack.floats(0.0f);
STBTTAlignedQuad q = STBTTAlignedQuad.mallocStack(stack);
glScalef(this.scale, this.scale,
this.scale);
glBegin(GL_QUADS);
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
y.put(0, y.get(0) + FONT_HEIGHT);
x.put(0, 0.0f);
continue;
} else if (c < 32 || 128 <= c)
continue;
stbtt_GetBakedQuad(cdata, BITMAP_W, BITMAP_H, c - 32, x, y, q, true);
glTexCoord2f(q.s0(), q.t0());
glVertex2f(q.x0(), q.y0());
glTexCoord2f(q.s1(), q.t0());
glVertex2f(q.x1(), q.y0());
glTexCoord2f(q.s1(), q.t1());
glVertex2f(q.x1(), q.y1());
glTexCoord2f(q.s0(), q.t1());
glVertex2f(q.x0(), q.y1());
}
glEnd();
glScalef(1f, 1f, 1f);
}
which works fine, the text is rendered in the font.
So I try to work out the width of the string like so:
public float getWidth(String text) {
float maxWidth = 0;
try (MemoryStack stack = stackPush()) {
FloatBuffer x = stack.floats(0.0f);
FloatBuffer y = stack.floats(0.0f);
STBTTAlignedQuad q = STBTTAlignedQuad.mallocStack(stack);
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
y.put(0, y.get(0) + FONT_HEIGHT);
x.put(0, 0.0f);
continue;
} else if (c < 32 || 128 <= c)
continue;
stbtt_GetBakedQuad(cdata, BITMAP_W, BITMAP_H, c - 32, x, y, q, true);
if (q.s1() > maxWidth)
maxWidth = q.s1();
}
}
return maxWidth * this.scale;
}
but this returns a value much less than it should. Where am I going wrong here?