Benjin
Benjin

Reputation: 2409

How can I draw a centered string in OpenGL/C++?

void DrawGLText(string text, float loc_x, float loc_y) {
  glColor4f(1.0, 1.0, 1.0, 0.5);
  glRasterPos3f(loc_x, loc_y, 1);
  glutBitmapString(GLUT_BITMAP_HELVETICA_18), text.c_str());
}

This is the my code for drawing text at a specific location. I'd like to adapt it to draw text that's centered on (loc_x, loc_y) rather than left-aligned.

Upvotes: 1

Views: 1822

Answers (1)

genpfault
genpfault

Reputation: 52082

Use glutBitmapWidth() or glutBitmapLength() (from FreeGLUT) to find the width of your string and translate along the X axis by -textWidth / 2.0f:

// call glRasterPos*() before this
// x/y offsets are in pixels
void bitmapString( void* aFont, const unsigned char* aString, float aXoffset, float aYoffset )
{
    GLboolean valid = GL_FALSE;
    glGetBooleanv( GL_CURRENT_RASTER_POSITION_VALID, &valid );
    if( !valid )
    {
        return;
    }

    GLfloat pos[4] = { 0.0f };
    glGetFloatv( GL_CURRENT_RASTER_POSITION, pos );
    glWindowPos2f( pos[0] + aXoffset, pos[1] + aYoffset );
    glutBitmapString( aFont, aString );
}

// usage
std::string text = "Lorem ipsum";
glRasterPos2f( 50.0f, 100.0f );
const auto* str = reinterpret_cast<const unsigned char*>(text.c_str());
const int width = glutBitmapLength( font, str );
bitmapString( font, str, -width / 2.0f, 0.0f );

Upvotes: 2

Related Questions