我如何在OpenGL/ c++中绘制居中字符串
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());
}
这是我在特定位置绘制文本的代码。我想调整它来绘制以(loc_x, loc_y)为中心的文本,而不是左对齐。
使用glutBitmapWidth()
或glutBitmapLength()
(来自FreeGLUT)来查找字符串的宽度并通过-textWidth / 2.0f
沿X轴平移:
// 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 );