如何在OpenGL/C++中绘制居中字符串?

csga3l58  于 2022-09-26  发布在  其他
关注(0)|答案(1)|浏览(171)
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());
}

这是用于在特定位置绘制文本的My代码。我想调整它以绘制居中(loc_x,loc_y)而不是左对齐的文本。

epggiuax

epggiuax1#

使用glutBitmapWidth()glutBitmapLength()(来自FreeGLUT)计算字符串的宽度,并沿X轴平移-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 );

相关问题